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--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--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("&","&")).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. 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. Copyright (C) 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 . 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: Copyright (C) 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 . 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 . ================================================ 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: ## Description: 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: - 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: 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 ``` 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 -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 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 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: ## Description: 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: 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: ### 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: ### 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 chart gives you stats about object lifetimes in hours and a second one figures by ObjectClass. - Objects added or removed from groups or ACL modifications within timeframe: This table focuses on the Member and nTSecurityDescriptor attributes, which can help detect an elevation of privilege for a specific account or a backdoor setup by the attacker, the DistinguishedName value of the member and the time the member was added or removed from the group is given in that table. Which makes it more detailed than the above AD Timeline panel. A chart displaying nTSecurityDescriptor modifications by ObjectClass and another displaying the number of times an object was added or removed from a group are given - GPOs modifications within timeframe: A GPO can used by an attacker in various ways, for example to inject malicious code in logon/startup scripts, deploy malware at scale with an immediate scheduled task, setup a backdoor by modifying the nTSecurityDescriptor... For each attribute modification this table gives you the current client side extensions of the GPO and where the object is linked (OU, site or domain root). ### The track suspicious activity dashboard This dashboard analyses the Active Directory timeline and highlights some modifications which can be a sign of a suspicious activity, the modifications spoted can also be legitimate and need a triage analysis. The different panels are: - ACL modifications: This panel does not replace a thorough analysis of the Active Directory permissions with tools such as AD Control Paths. The panel contains a graph displaying a weekly timeline of ACL modifications per ObjectClass which occured one year back, some tables are focusing on the domain root and AdminSDHolder objects where permissions can be used as backdoor by an attacker. Finally, some statistics by ObjectClass and by least frequent owners are displayed. - Accounts: This panel show account modifications which can a be sign of suspicious activity such as users added and removed from groups, some charts provide stats by number of times the account was added or removed, membership time in days, Organizational unit where accounts are located (an account from the "non_privileged_users" OU added and removed from a privileged group can be a sign of suspicious activity). There are some graphs, the first graph shows a timeline of accounts lockouts in order to highlight brute force attacks, the second graph shows SID history editions which can be suspicious outside a domain migration period, the next graph analyses all the different attributes modified on an account during a password change (supplementalCredentials, lmPwdHistory, unicodePwd...) and checks they are modified at the same time. A table displays resource based constrained delegation setup on privileged account or domain controller computer objects, which can be a backdoor setup by an attacker. Finally a chart displays domain controller computer objects password change frequency, an attacker could modify the DC registry to disable computer password change and use this password as a backdoor. - GPOs: A table of GPOs modifications having an audit client side extension is displayed, an attacker could change the audit settings on the domain to perform malicious actions with stealth. Finally modifications which could result in a GPO processing malfunctioning are displayed, this includes gPCFunctionalityVersion, gPCFileSysPath or versionNumber attribute modification. - DCshadow detection: The DCshadow is an attack which allows an attacker to push modifications in Active Directory and bypass traditional alerting by installing a fake DC. It was first presented by Vincent Le Toux and Benjamin Delpy at the BlueHat IL 2018 conference. The first graph will try to detect the installation of the fake DC by analyzing server and nTDSDSA ObjectClass. The two following tables will try to detect replication metadata tampering by analyzing usnOriginatingChange and usnLocalChange values which should increment through the time. - Schema and configuration partition suspicious modifications: The first graph displays Active Directory attribute modifications related to the configuration and schema partitions which can lower the security of the domain, used as backdoor by an attacker or hide information to the security team. The second graph is relevant if you have Exchange on premises and track modifications in the configuration partition which can be a sign of mail exfiltration. ### The track suspicious Exchange activity dashboard This dashboard analyses your Exchange onprem Active Directory objects and highlights some modifications which can be a sign of a suspicious activity, the modifications spotted can also be legitimate and need a triage analysis. The different panels are: - Microsoft Exchange infrastructure: Exchange version and servers. - Possible mail exfiltration: Mail forwarders setup on mailboxes, transport rules, remote domains, maibox export requests, content searches... - Persistence: RBAC roles and ACL modifications on Exchange objects. - MsExchangeSecurityGroups: Timeline and group membership of builtin Exchange security groups. - Phishing:Modifications on transport rules related to SCL and disclaimer. ## Enhance your traditional event logs threat hunting with ADTimeline: The *adobjects* sourcetype is a set of data which can be used to uncover suspicious activity by performing Active Directory educated queries on the Windows event logs. We assume the sourcetype used for event logs is called *winevent* and its *EventData* part has the correct field extraction applied, for example *EventID 4624* has among other fields *TargetUserName* and *TargetUserSid* extracted: ![EVtx](./SA-ADTimeline/appserver/static/images/tuto10.png) You can perfrom similar queries with the [Splunk App for Windows Infrastructure](https://docs.splunk.com/Documentation/MSApp/2.0.0/Reference/Aboutthismanual) and the [Splunk Supporting Add-on for Active Directory](https://docs.splunk.com/Documentation/SA-LdapSearch/3.0.0/User/AbouttheSplunkSupportingAdd-onforActiveDirectory). Here are some queries using ADTimeline data and Windows event logs which can help with your threat hunt. - Statistics on privileged accounts logons: ```vb index="*" sourcetype="winevent" EventID="4624" Channel="Security" [ search index="*" sourcetype=adobjects ((ObjectClass = "user" OR ObjectClass = "inetOrgPerson") AND adminCount=1) earliest = 1 latest = now() | rename SID as TargetUserSid | fields TargetUserSid ] | strcat TargetDomainName "\\" TargetUserName TargetFullName | stats values(TargetFullName) as TargetFullName , values(LogonType) as logonTypes, values(IpAddress) as IpAdresses, values(Computer) as Computers, dc(Computer) as CountComputers, dc(IpAddress) as CountIpAdresses by TargetUserSid ``` - Get processes running under a privileged account, [detailed process auditing](https://docs.microsoft.com/en-us/windows-server/identity/ad-ds/manage/component-updates/command-line-process-auditing) should be enabled: ```vb index="*" sourcetype="winevent" EventID="4688" Channel="Security" [search index="*" sourcetype=adobjects ((ObjectClass = "user" OR ObjectClass = "inetOrgPerson") AND adminCount=1) earliest = 1 latest = now() | rename SamAccountName as TargetUserName | fields TargetUserName] OR [search index="*" sourcetype=adobjects ((ObjectClass = "user" OR ObjectClass = "inetOrgPerson") AND adminCount=1) earliest = 1 latest = now() | rename SID as SubjectUserSid | fields SubjectUserSid] | stats values(CommandLine) by Computer, TargetUserName,SubjectUserName ``` - Get all privileged accounts PowerShell activity eventlogs: ```vb index="*" sourcetype="winevent" Channel="*PowerShell*" [search index="*" sourcetype=adobjects ((ObjectClass = "user" OR ObjectClass = "inetOrgPerson") AND adminCount=1) earliest = 1 latest = now() | dedup SamAccountName | return 1000 $SamAccountName] ``` - Detect Kerberoasting possible activity: ```vb index="*" sourcetype="winevent" Channel="Security" EventID="4769" [search index="*" sourcetype=adobjects (ObjectClass = "user" OR ObjectClass = "inetOrgPerson") AND (SPNs=* AND NOT Name=krbtgt) earliest = 1 latest = now() | rename SID as ServiceSid | fields ServiceSid] | strcat TargetDomainName "\\" TargetUserName TargetFullName | eval time=strftime(_time,"%Y-%m-%d %H:%M:%S") | stats list(ServiceName) as Services, dc(ServiceName) as nbServices, list(time) as time by IpAddress, TicketEncryptionType | sort -nbServices ``` - Detect abnormal processes running under Kerberoastable accounts, [detailed process auditing](https://docs.microsoft.com/en-us/windows-server/identity/ad-ds/manage/component-updates/command-line-process-auditing) should be enabled: ```vb index="*" sourcetype="winevent" Channel="Security" EventID="4688" [search index="*" sourcetype=adobjects (ObjectClass = "user" OR ObjectClass = "inetOrgPerson") AND (SPNs=* AND NOT Name=krbtgt) earliest = 1 latest = now() | rename SamAccountName as TargetUserName | fields TargetUserName ] OR [search index="*" sourcetype=adobjects (ObjectClass = "user" OR ObjectClass = "inetOrgPerson") AND (SPNs=* AND NOT Name=krbtgt) earliest = 1 latest = now() | rename SID as SubjectUserSid | fields SubjectUserSid ] | stats values(CommandLine) as cmdlines, values(TargetUserName) as TargetSubjectNames, values(SubjectUserName) as SubjectUserNames by Computer ``` - Detect abnormal Kerberoastable user account logons: ```vb index="*" sourcetype="winevent" Channel="Security" EventID="4624" [search index="*" sourcetype=adobjects (ObjectClass = "user" OR ObjectClass = "inetOrgPerson") AND (SPNs=* AND NOT Name=krbtgt) earliest = 1 latest = now() | rename SID as TargetUserSid | fields TargetUserSid] | strcat TargetDomainName "\\" TargetUserName TargetFullName | stats values(TargetFullName) as TargetFullNames, values(IpAddress) as IpAddresses by LogonType, Computer ``` - Detect abnormal AS-REP roastable user account logons: ```vb index="*" sourcetype="winevent" Channel="Security" EventID="4624" [search index="*" sourcetype=adobjects (ObjectClass = "user" OR ObjectClass = "inetOrgPerson") earliest = 1 latest = now() | eval eval_asrep_bit = floor(userAccountControl / pow(2, 22)) %2 | search eval_asrep_bit = 1 | rename SID as TargetUserSid | fields TargetUserSid] | strcat TargetDomainName "\\" TargetUserName TargetFullName | stats values(TargetFullName) as TargetFullNames, values(IpAddress) as IpAddresses by LogonType, Computer ``` - Privileged accounts with flag "cannot be delegated" not set authenticating against computer configured for unconstrained delegation: ```vb index="*" sourcetype="winevent" EventID="4624" Channel="Security" [search index="*" sourcetype=adobjects ObjectClass = "Computer" earliest = 1 latest = now() | eval eval_deleg_bit = floor(userAccountControl / pow(2, 19)) %2 | search eval_deleg_bit = 1 | eval eval_dc_bit = floor(userAccountControl / pow(2, 13)) %2 | eval eval_rodc_bit = floor(userAccountControl / pow(2, 26)) %2 | search eval_dc_bit = 0 AND eval_rodc_bit = 0 | rename dNSHostName as Computer | fields Computer] | search * [search index="*" sourcetype=adobjects ((ObjectClass = "user" OR ObjectClass = "inetOrgPerson") AND adminCount=1) earliest = 1 latest = now() | eval canbedelagated = round(((userAccountControl / pow(2, 20)) %2), 0) | search canbedelagated = 0 | rename SID as TargetUserSid | fields TargetUserSid ] | strcat TargetDomainName "\\" TargetUserName TargetFullName | table _time, Computer, TargetFullName, IpAddress, LogonType, LogonProcessName ``` - Detect possible [printer bug](https://posts.specterops.io/not-a-security-boundary-breaking-forest-trusts-cd125829518d) triggering: ```vb index="*" sourcetype="winevent" EventID="4624" Channel="Security" TargetUserName = "*$" NOT TargetUserSid="S-1-5-18" [search index="*" sourcetype=adobjects ObjectClass = "Computer" earliest = 1 latest = now() | eval eval_deleg_bit = floor(userAccountControl / pow(2, 19)) %2 | search eval_deleg_bit = 1 | eval eval_dc_bit = floor(userAccountControl / pow(2, 13)) %2 | eval eval_rodc_bit = floor(userAccountControl / pow(2, 26)) %2 | search eval_dc_bit = 0 AND eval_rodc_bit = 0 | rename dNSHostName as Computer | fields Computer] | strcat TargetDomainName "\\" TargetUserName TargetFullName | stats values(LogonType), values(IpAddress), values(LogonProcessName) count by Computer, TargetFullName ``` ================================================ FILE: SA-ADTimeline/README ================================================ Contact information: adtimeline@ssi.gouv.fr There is no package requirements to install the app. This is an open source project, no support provided, public repository available at https://github.com/ANSSI-FR/ADTimeline/ Please have a look at the "Getting started" tab for detailed instructions. ================================================ FILE: SA-ADTimeline/default/app.conf ================================================ # # Splunk app configuration file # [package] id = SA-ADTimeline check_for_updates = true [install] is_configured = 0 [ui] is_visible = 1 label = ADTimeline [launcher] author = Leonard SAVINA (@ldap389) - Nicolas LE CHAPELAIN description = ADTimeline app for Splunk is an open source project, code is available at https://github.com/ANSSI-FR/ADTimeline version = 1.2.5 [id] name = SA-ADTimeline version = 1.2.5 ================================================ FILE: SA-ADTimeline/default/data/ui/nav/default.xml ================================================ ================================================ FILE: SA-ADTimeline/default/data/ui/views/ad_infra.xml ================================================
| tstats latest(_time) where index=* by index true index index | tstats latest(_time) where index=$ad_index$ (sourcetype=adobjects OR sourcetype=gcobjects OR sourcetype=adtimeline) by host true host host

General information: AD schema version, ObjectVersion attribute of dMD ObjectClass: index=$ad_index$ host=$domain_host$ sourcetype=adobjects ObjectClass=dMD | rex field=_raw "objectVersion\">(?<ObjectVersion>.+?)</I32>" | lookup Schema_lookup ObjectVersion AS ObjectVersion OUTPUTNEW SchemaVersion AS SchemaV | eval range = case ( ObjectVersion < 48, "severe", ObjectVersion < 69, "elevated" , ObjectVersion < 1000 , "low" ) $earliest$ $latest$ search?q=index=$ad_index$%20host=$domain_host$%20(sourcetype=adobjects%20OR%20sourcetype=adtimeline)%20ObjectClass=dMD&earliest=$earliest$&latest=$latest$ ]]> AD forest and domain functional level, msDS-Behavior-Version atribute: index=$ad_index$ host=$domain_host$ sourcetype=adobjects ObjectClass = "crossref" OR ObjectClass = "crossrefcontainer" | rex field=_raw "systemFlags\">(?<systemFlags>.+?)</I32>" | search systemFlags = "3" OR ObjectClass = "crossrefcontainer" | rex field=_raw "msDS-Behavior-Version\">(?<msDSBehaviorVersion>.+?)</I32>" | eval Name=case(Name == "Partitions", "FOREST FUNCTIONAL LEVEL", 1=1 , Name ) | stats count by msDSBehaviorVersion, Name $earliest$ $latest$

Windows 2000=0 | Windows 2003 Interim=1 | Windows 2003=2 | Windows 2008=3 | Windows 2008R2=4
Windows 2012=5 | Windows 2012 R2=6 | Windows 2016=7 | Windows 2019=7

DCs in the current domain, computer ObjectClass: index=$ad_index$ host=$domain_host$ sourcetype=adobjects OR sourcetype=gcobjects ObjectClass= "Computer" DN = "*,OU=Domain Controllers,*" | eval eval_dc_bit = floor(userAccountControl / pow(2, 13)) %2 | eval eval_rodc_bit = floor(userAccountControl / pow(2, 26)) %2 | search eval_dc_bit = 1 OR eval_rodc_bit = 1 | rex field=_raw "operatingSystem\">(?<operatingSystem>.+?)</S>" | stats count by Name, operatingSystem, whenCreated | rename Name as "DC name", operatingSystem as "DC operating system", whenCreated as "DC creation time" | table "DC name", "DC operating system", "DC creation time" 0 search?q=index=$ad_index$%20host=$domain_host$%20sourcetype=adobjects%20OR%20sourcetype=gcobjects%20OR%20sourcetype=adtimeline%20ObjectClass=%20%22Computer%22%20DN%20=%20%22*,OU=Domain%20Controllers,*%22&earliest=$earliest$&latest=$latest$
FSMO roles, fSMORoleOwner attribute: index=$ad_index$ host=$domain_host$ sourcetype=adobjects (ObjectClass= "DomainDNS" OR ObjectClass= "dMD" OR ObjectClass= "rIDManager" OR ObjectClass= "crossRefContainer" OR ObjectClass= "infrastructureUpdate") | rex field=_raw "<S N=\"fSMORoleOwner\">CN=NTDS Settings,(?<fsmoroleowner>.+?)</S>" | lookup fsmo_lookup ObjectClass AS ObjectClass OUTPUTNEW FSMORole AS FSMORole | table FSMORole, fsmoroleowner, ObjectClass $earliest$ $latest$ search?q=index=$ad_index$%20host=$domain_host$%20(sourcetype=adobjects%20OR%20sourcetype=adtimeline)%20(ObjectClass=%20%22DomainDNS%22%20OR%20ObjectClass=%20%22dMD%22%20OR%20ObjectClass=%20%22rIDManager%22%20OR%20ObjectClass=%20%22crossRefContainer%22%20OR%20ObjectClass=%20%22infrastructureUpdate%22)%20OR%20%5Bsearch%20index%20=%20%22ad%22%20sourcetype=adobjects%20(ObjectClass=%20%22DomainDNS%22%20OR%20ObjectClass=%20%22dMD%22%20OR%20ObjectClass=%20%22rIDManager%22%20OR%20ObjectClass=%20%22crossRefContainer%22%20OR%20ObjectClass=%20%22infrastructureUpdate%22)%20%7C%20rex%20field=_raw%20%22%3CS%20N=%5C%22fSMORoleOwner%5C%22%3ECN=NTDS%20Settings,(%3F%3Cfsmoroleowner%3E.%2B%3F)%3C/S%3E%22%20%7C%20%20%20stats%20count%20by%20fsmoroleowner%20%7C%20eval%20DN%20=%20fsmoroleowner%20%7C%20table%20DN%5D&earliest=$earliest$&latest=$latest$
Microsoft infrastructure products: Microsoft Exchange schema information, rangeUpper attribute of ms-Exch-Schema-Version-Pt object: index=$ad_index$ host=$domain_host$ sourcetype=adobjects (ObjectClass=attributeSchema AND Name=ms-Exch-Schema-Version-Pt) | table Name | appendpipe [stats count | eval "Name"="Void" | where count=0 | table "Name"] | eval checkExch =case(Name == "ms-Exch-Schema-Version-Pt", "Exchange installed in the AD forest", 1=1 , "Exchange not installed in the AD forest") | fields checkExch $earliest$ $latest$ search?q=index=$ad_index$%20host=$domain_host$%20(sourcetype=adobjects%20OR%20sourcetype=gcobjects%20OR%20sourcetype=adtimeline)%20((Name%20=%20%22Exchange%20Trusted%20Subsystem%22%20AND%20ObjectCategory=%20%22CN=Group,CN=Schema,CN=Configuration*%22)%20OR%20ObjectClass=%20%22msExchExchangeServer%22%20OR%20(ObjectClass=attributeSchema%20AND%20Name=ms-Exch-Schema-Version-Pt)%20)&earliest=$earliest$&latest=$latest$ ]]> index=$ad_index$ host=$domain_host$ sourcetype=adobjects (ObjectClass=attributeSchema AND Name=ms-Exch-Schema-Version-Pt) | rex field=_raw "rangeUpper\">(?<rangeUpper>.+?)</I32>" | lookup ExchangeSchema_lookup rangeUpper AS rangeUpper OUTPUTNEW Exchange AS ExchangeV | stats count by ExchangeV, rangeUpper | rangemap field=rangeUpper low=15331-1000000 elevated=15312-15331 default=severe $earliest$ $latest$ Microsoft Exchange servers, msExchExchangeServer ObjectClass: index=$ad_index$ host=$domain_host$ sourcetype=adobjects ObjectClass=msExchExchangeServer | rex field=_raw "<S>Version (?<ExchVersion>.+?)</S>" | stats count by Name, ExchVersion, whenCreated | rename Name as "Exchange server name", ExchVersion as "Exchange server version", whenCreated as "Exchange server creation time" | table "Exchange server name", "Exchange server version", "Exchange server creation time" 0 toto search?q=index=$ad_index$%20host=$domain_host$%20(sourcetype=adobjects%20OR%20sourcetype=gcobjects%20OR%20sourcetype=adtimeline)%20ObjectClass=msExchExchangeServer&earliest=$earliest$&latest=$latest$

Microsoft Exchange servers, msExchExchangeServer ObjectClass: No results

]]> Microsoft ADFS Information, ADFS container: index=$ad_index$ host=$domain_host$ sourcetype=adobjects OR sourcetype=gcobjects (DN ="CN=ADFS,CN=Microsoft,CN=Program Data*") | table Name | appendpipe [stats count | eval "Name"="Void" | where count=0 | table "Name"] | eval checkADFS =case(Name == "ADFS", "ADFS installed in the AD Forest", 1=1 , "ADFS not installed in the AD forest") | fields checkADFS $earliest$ $latest$ search?q=index=$ad_index$%20host=$domain_host$%20sourcetype=adobjects%20OR%20sourcetype=gcobjects%20OR%20sourcetype=adtimeline%20(DN%20=%22*CN=ADFS,CN=Microsoft,CN=Program%20Data*%22)&earliest=$earliest$&latest=$latest$ ]]> Microsoft ADCS information, certificationAuthority ObjectClass: index=$ad_index$ host=$domain_host$ sourcetype=adobjects ObjectClass=certificationAuthority (DN ="*,CN=Certification Authorities,CN=Public Key Services,CN=Services,*" OR DN ="*CN=NTAuthCertificates,CN=Public Key Services,CN=Services,CN=Configuration,*") | table ObjectClass, DN, Name | appendpipe [stats count | eval "ObjectClass"="Void", "DN"="Void", "Name"="Void" | where count=0 | table "ObjectClass"] | eval CAName = "\"" + Name + "\" entreprise CA configured" | eval checkEntCA =case(ObjectClass == "certificationAuthority" AND DN LIKE "%CN=Certification Authorities%", CAName, ObjectClass == "certificationAuthority" AND DN LIKE "%CN=NTAuthCertificates,%" , " NTAuthCertificates for smartcard logon configured" , 1=1 , "No CA configured") | stats values(checkEntCA) as checkEntCA | mvexpand checkEntCA | rename checkEntCA as "Cert Authorities configured" $earliest$ $latest$ search?q=index=$ad_index$%20host=$domain_host$%20sourcetype=adobjects%20OR%20sourcetype=gcobjects%20OR%20sourcetype=adtimeline%20ObjectClass=certificationAuthority&earliest=$earliest$&latest=$latest$
ADCS Enrollment servers, pKIEnrollmentService ObjectClass: index=$ad_index$ host=$domain_host$ sourcetype=adobjects ObjectClass=pKIEnrollmentService | rex field=_raw "cACertificateDN\">(?<cACertificateDN>.+?)</S>" | stats count by dNSHostName, cACertificateDN, whenCreated | rename dNSHostName as "ADCS server name", cACertificateDN as "CA Name", whenCreated as "ADCS server installation time" | table "ADCS server name", "CA Name" , "ADCS server installation time" $earliest$ $latest$ toto search?q=index=$ad_index$%20host=$domain_host$%20(sourcetype=adobjects%20OR%20sourcetype=gcobjects%20OR%20sourcetype=adtimeline)%20ObjectClass=pKIEnrollmentService&earliest=$earliest$&latest=$latest$

ADCS Enrollment servers, pKIEnrollmentService ObjectClass: No results

Domain Trusts: Trusts types, trustedDomain objectClass: index=$ad_index$ host=$domain_host$ sourcetype=adobjects ObjectClass=trustedDomain | rex field=_raw "trustAttributes\">(?<trustAttributes>.+?)</I32>" | rex field=_raw "trustDirection\">(?<trustDirection>.+?)</I32>" | eval trust=case( floor(trustAttributes / pow(2, 5)) %2 == 1 , "Forest internal", (trustAttributes / pow(2, 2)) %2 == 1 , "Quarantined domain - SID filtering enabled", (trustAttributes / pow(2, 6)) %2 == 1 , "Treat as external trust - SID history enabled" , 1=1 , "Other type of trust") | eval direction = case(trustDirection == 0, "disabled", trustDirection == 1, "inbound", trustDirection == 2, "outbound", 1=1, "bidirectional") | eval trusttype = trust + "-" + direction | stats count as "Trust types" by trusttype $earliest$ $latest$ toto search?q=index=$ad_index$%20host=$domain_host$%20sourcetype=adobjects%20%20ObjectClass=trustedDomain%20%7C%20rex%20field=_raw%20%22trustAttributes%5C%22%3E(%3F%3CtrustAttributes%3E.%2B%3F)%3C/I32%3E%22%20%7C%20rex%20field=_raw%20%22trustDirection%5C%22%3E(%3F%3CtrustDirection%3E.%2B%3F)%3C/I32%3E%22%20%7C%20eval%20trust=case(%20floor(trustAttributes%20/%20pow(2,%205))%20%252%20==%201%20,%20%22Forest%20internal%22,%20(trustAttributes%20/%20pow(2,%202))%20%252%20==%201%20,%20%22Quarantined%20domain%20-%20SID%20filtering%20enabled%22,%20%20(trustAttributes%20/%20pow(2,%206))%20%252%20==%201%20,%20%22Treat%20as%20external%20trust%20-%20SID%20history%20enabled%22%20,%201=1%20,%20%22Other%20type%20of%20trust%22)%20%7C%20eval%20direction%20=%20case(trustDirection%20==%200,%20%22disabled%22,%20trustDirection%20==%201,%20%22inbound%22,%20trustDirection%20==%202,%20%22outbound%22,%201=1,%20%22bidirectional%22)%20%7C%20eval%20trusttype%20=%20trust%20%2B%20%22-%22%20%2B%20direction%20%0A%7C%20%20search%20$click.name$%20=%20%22$click.value$%22&earliest=$earliest$&latest=$latest$

Trusts types, trustedDomain objectClass: No results

Trusts list, trustedDomain objectClass: index=$ad_index$ host=$domain_host$ sourcetype=adobjects ObjectClass=trustedDomain | rex field=_raw "trustAttributes\">(?<trustAttributes>.+?)</I32>" | rex field=_raw "trustDirection\">(?<trustDirection>.+?)</I32>" | rex field=_raw "AccountDomainSid\">(?<AccountDomainSid>.+?)</S>" | eval trust = mvappend ( if ( floor(trustAttributes / pow(2, 0)) %2 == 1 , "Non transitive" , null() ), if ( floor(trustAttributes / pow(2, 1)) %2 == 1 , "Uplevel only" , null() ) , if ( floor(trustAttributes / pow(2, 2)) %2 == 1 , "Quarantined domain - SID filtering enabled" , null() ) , if ( floor(trustAttributes / pow(2, 3)) %2 == 1 , "Forest Transitive" , null() ) , if ( floor(trustAttributes / pow(2, 4)) %2 == 1 , "Cross org trust" , null() ) , if ( floor(trustAttributes / pow(2, 5)) %2 == 1 , "Forest internal" , null() ), if ( floor(trustAttributes / pow(2, 6)) %2 == 1 , "Treat as external trust - SID history enabled" , null() ), if ( floor(trustAttributes / pow(2, 7)) %2 == 1 , "Uses RC4 encryption" , null() ) , if ( floor(trustAttributes / pow(2, 8)) %2 == 1 , "Uses AES encryption" , null() ) , if ( floor(trustAttributes / pow(2, 9)) %2 == 1 , "Cross org trust with no TGT delegation" , null() ) , if ( floor(trustAttributes / pow(2, 10)) %2 == 1 , "Treat as external trust with Privileged Identity Management" , null() )) | eval direction = case(trustDirection == 0, "disabled", trustDirection == 1, "inbound", trustDirection == 2, "outbound", 1=1, "bidirectional") | rename Name as "Trust partner", AccountDomainSid as "Trust partner SID", trust as "trust type", whenCreated as "trust creation time", direction as "trust direction" | table "Trust partner", trustAttributes, "trust direction", "trust type", "trust creation time", "Trust partner SID" $earliest$ $latest$ toto search?q=index=$ad_index$%20host=$domain_host$%20(sourcetype=adobjects%20OR%20sourcetype=gcobjects%20OR%20sourcetype=adtimeline)%20ObjectClass=TrustedDomain&earliest=$earliest$&latest=$latest$

Trusts list, trustedDomain objectClass: No results

ADDS security features: Recycle bin, crossRefContainer objectClass: index=$ad_index$ host=$domain_host$ ObjectClass = "crossRefContainer" sourcetype=adobjects DN = "CN=Partitions,CN=Configuration,*" | rex field=_raw "<S>(?<optionalfeature>.+?)</S>" | eval Recycle =case(optionalfeature like "%Recycle Bin Feature%", "Recycle Bin feature is enabled"), Recyclevalue =case(optionalfeature like "%Recycle Bin Feature%", 1) | fillnull Recycle value="Recycle Bin feature is disabled"| fillnull Recyclevalue value=0 | table Recycle, Recyclevalue | stats count by Recycle, Recyclevalue | rangemap field=Recyclevalue low=1-2 default=severe $earliest$ $latest$ search?q=index=$ad_index$%20host=$domain_host$%20(sourcetype=adobjects%20OR%20sourcetype=gcobjects%20OR%20sourcetype=adtimeline)%20ObjectClass=crossRefContainer&earliest=$earliest$&latest=$latest$ ]]> LAPS, attributeSchema objectClass: index=$ad_index$ host=$domain_host$ sourcetype=adobjects ObjectClass=attributeSchema Name=ms-Mcs-AdmPwd | table Name | appendpipe [stats count | eval "Name"="Void" | where count=0 | table "Name"] | eval LAPS =case(Name == "ms-Mcs-AdmPwd", "LAPS schema extension done", 1=1, "Schema not setup for LAPS"), LAPSValue = case(Name == "ms-Mcs-AdmPwd", 1, 1=1 ,0) | stats count by LAPS, LAPSValue | rangemap field=LAPSValue low=1-2 default=elevated $earliest$ $latest$ search?q=index=$ad_index$%20host=$domain_host$%20(sourcetype=adobjects%20OR%20sourcetype=gcobjects%20OR%20sourcetype=adtimeline)%20ObjectClass=attributeSchema%20Name=ms-Mcs-AdmPwd&earliest=$earliest$&latest=$latest$ ]]> Authentication silos, msDS-AuthNPolicySilo and msDS-AuthNPolicy objectClass: index=$ad_index$ host=$domain_host$ sourcetype=adobjects (ObjectClass=msDS-AuthNPolicySilo OR ObjectClass=msDS-AuthNPolicy) | table ObjectClass | appendpipe [stats count | eval "ObjectClass"="Void" | where count=0 | table "ObjectClass"] | eval Silo =case(ObjectClass == "msDS-AuthNPolicy" OR ObjectClass == "msDS-AuthNPolicySilo" , "Authentication silos configured, check also if DFL is greater or equal 6", 1=1, "No authentication silos configured"), SiloValue = case(ObjectClass == "msDS-AuthNPolicy" OR ObjectClass == "msDS-AuthNPolicySilo", 1, 1=1 ,0) | stats count by Silo, SiloValue | rangemap field=SiloValue low=1-2 default=elevated $earliest$ $latest$ search?q=index=$ad_index$%20host=$domain_host$%20(sourcetype=adobjects%20OR%20sourcetype=gcobjects%20OR%20sourcetype=adtimeline)%20(ObjectClass=msDS-AuthNPolicySilo%20OR%20ObjectClass=msDS-AuthNPolicy)&earliest=$earliest$&latest=$latest$ ]]> Protected Users group, memberOf attribute: index=$ad_index$ host=$domain_host$ sourcetype=adobjects MemberOf = "*CN=Protected Users,CN=Users*" | stats count | eval Protected= if(count > 0,"Protected users group has members, check also DFL","Protected users group has no members"), ProtectedValue= if(count > 0,1,0) | stats count by Protected, ProtectedValue | rangemap field=ProtectedValue low=1-2 default=elevated $earliest$ $latest$ search?q=index=$ad_index$%20%20host=$domain_host$%20%20sourcetype=adobjects%20MemberOf%20=%20%22*CN=Protected%20Users,CN=Users*%22&earliest=$earliest$&latest=$latest$
Service Connection Points: SCPs in the configuration partition: toto index=$ad_index$ host=$domain_host$ (sourcetype="adobjects" OR sourcetype="gcobjects") DN = "*,CN=Services,CN=Configuration,*" ObjectCategory = "CN=Service-Connection-Point,CN=Schema,CN=Configuration,*" | eval keyword = replace(keywords, "(<(.|)S>|[\\n\\r])" , "") | eval serviceBindingInformations = replace(serviceBindingInformation, "(<(.|)S>|[\\n\\r])" , "") | rename keyword as keywords, serviceBindingInformations as serviceBindingInformation | table DN, keywords, serviceBindingInformation $earliest$ $latest$ search?q=index=$ad_index$%20host=$domain_host$%20(sourcetype=%22adobjects%22%20OR%20sourcetype=%22gcobjects%22)%20DN%20=%20%22*,CN=Services,CN=Configuration,*%22%20ObjectCategory%20=%20%22CN=Service-Connection-Point,CN=Schema,CN=Configuration,*%22&earliest=$earliest$&latest=$latest$

SCPs in the configuration partition: No results

SCPs in the domain partition: toto index=$ad_index$ host=$domain_host$ sourcetype="adobjects" ObjectClass="serviceConnectionPoint" OR ObjectClass="mSSMSManagementPoint" OR ObjectClass="intellimirrorSCP" OR ObjectClass="serviceAdministrationPoint" NOT DN = "*,CN=Services,CN=Configuration,*" | eval keyword = replace(keywords, "(<(.|)S>|[\\n\\r])" , "") | eval serviceBindingInformations = replace(serviceBindingInformation, "(<(.|)S>|[\\n\\r])" , "") | rename keyword as keywords, serviceBindingInformations as serviceBindingInformation | eval keywords_length = len(keywords) | fillnull keywords_length value=160 | sort keywords_length, -serviceClassName | table DN, serviceClassName, ObjectClass, keywords, serviceBindingInformation $earliest$ $latest$ search?q=index=$ad_index$%20host=$domain_host$%20sourcetype=%22adobjects%22%20ObjectClass=%22serviceConnectionPoint%22%20OR%20ObjectClass=%22mSSMSManagementPoint%22%20OR%20ObjectClass=%22intellimirrorSCP%22%20OR%20ObjectClass=%22serviceAdministrationPoint%22%20NOT%20DN%20=%20%22*,CN=Services,CN=Configuration,*%22%20%7C%20%20eval%20keyword%20=%20replace(keywords,%20%22(%3C(.%7C)S%3E%7C%5B%5C%5Cn%5C%5Cr%5D)%22%20,%20%22%22)%20%7C%20%20eval%20serviceBindingInformations%20=%20replace(serviceBindingInformation,%20%22(%3C(.%7C)S%3E%7C%5B%5C%5Cn%5C%5Cr%5D)%22%20,%20%22%22)%20%20%7C%20rename%20keyword%20as%20keywords,%20serviceBindingInformations%20as%20serviceBindingInformation%20%0A%20%20%20%20%7C%20search%20$click.name2$%20=%20%22$click.value2$%22&earliest=$earliest$&latest=$latest$

SCPs in the domain partition: No results

Active Directory infrastructure timeline: index=$ad_index$ host=$domain_host$ sourcetype=adtimeline ((ObjectClass=DomainDNS OR (ObjectClass=container AND Name="AdminSDHolder")) AND (pszAttributeName = "whencreated" OR pszAttributeName = "ntsecuritydescriptor" OR pszAttributeName = "fsmoRoleOwner")) OR (ObjectClass=crossref AND pszAttributeName="msDS-Behavior-Version") OR (Name = "Exchange Trusted Subsystem" AND ObjectCategory="CN=Group,CN=Schema,CN=Configuration*" AND (pszAttributeName = "whencreated" OR pszAttributeName = "msExchGroupMemberCount")) OR (ObjectClass= "dMD" AND (pszAttributeName= "objectVersion" OR pszAttributeName= "fsmoRoleOwner")) OR (((ObjectClass= "infrastructureUpdate" AND Name= "infrastructure") OR ObjectClass= "rIDManager" OR (ObjectClass= "crossRefContainer" AND Name= "Partitions")) AND (pszAttributeName = "fsmoRoleOwner" OR pszAttributeName = "optionalfeature")) OR (ObjectClass= "trustedDomain" AND pszAttributeName = "whencreated") OR (ObjectClass = "container" AND DN = "CN=ADFS,CN=Microsoft,CN=Program Data*" AND pszAttributeName = "whencreated") OR ( ObjectClass = "msExchSystemObjectsContainer" AND Name = "Microsoft Exchange System Objects" AND pszAttributeName = "ObjectVersion") OR (ObjectClass = "attributeSchema" AND Name=ms-Mcs-AdmPwd AND pszAttributeName = "whencreated") OR ((ObjectClass = "msDS-AuthNPolicySilo" OR ObjectClass = "msDS-AuthNPolicy") AND pszAttributeName = "whencreated") OR (ObjectClass = "certificationAuthority" AND ((DN ="*,CN=Certification Authorities,CN=Public Key Services,CN=Services,*" AND pszAttributeName = "whencreated") OR (DN ="*CN=NTAuthCertificates,CN=Public Key Services,CN=Services,CN=Configuration,*" AND pszAttributeName = "cACertificate"))) OR (ObjectClass = "attributeSchema" AND Name = "ms-Exch-Schema-Version-Pt" AND pszAttributeName = "rangeUpper") OR ((ObjectCategory = "CN=Service-Connection-Point,CN=Schema,CN=Configuration,*" OR ObjectClass="mSSMSManagementPoint" OR ObjectClass="intellimirrorSCP" OR ObjectClass="serviceAdministrationPoint") AND pszAttributeName = "WhenCreated") | makemv pszLastOriginatingDsaDN delim=",CN=" | eval OriginatingDC = mvindex(pszLastOriginatingDsaDN, 1, 1) | table _time, DN, ObjectClass, pszAttributeName, dwVersion, OriginatingDC | sort -_time 0 search?q=index=$ad_index$%20host=$domain_host$%20sourcetype=adtimeline%20((ObjectClass=DomainDNS%20OR%20(ObjectClass=container%20AND%20Name=%22AdminSDHolder%22)%20OR%20ObjectClass=%22crossref%22%20OR%20(Name%20=%20%22Exchange%20Trusted%20Subsystem%22%20AND%20ObjectCategory=%22CN=Group,CN=Schema,CN=Configuration*%22)%20OR%20ObjectClass=%20%22dMD%22%20OR%20(ObjectClass=%20%22infrastructureUpdate%22%20AND%20Name=%20%22infrastructure%22)%20OR%20ObjectClass=%20%22trustedDomain%22%20OR%20(ObjectClass%20=%20%22container%22%20AND%20DN%20=%20%22CN=ADFS,CN=Microsoft,CN=Program%20Data*%22)%20OR%20(%20ObjectClass%20=%20%22msExchSystemObjectsContainer%22%20AND%20Name%20=%20%22Microsoft%20Exchange%20System%20Objects%22)%20OR%20(ObjectClass%20=%20%22attributeSchema%22%20AND%20%20Name=ms-Mcs-AdmPwd)%20OR%20ObjectClass%20=%20%22msDS-AuthNPolicySilo%22%20OR%20%20ObjectClass%20=%20%22msDS-AuthNPolicy%22%20OR%20ObjectClass%20=%20%22certificationAuthority%22%20%20OR%20(ObjectClass%20=%20%22attributeSchema%22%20AND%20Name%20=%20%22ms-Exch-Schema-Version-Pt%22%20)))%20OR%20((ObjectCategory%20=%20%22CN=Service-Connection-Point,CN=Schema,CN=Configuration,*%22%20%20OR%20ObjectClass=%22mSSMSManagementPoint%22%20OR%20ObjectClass=%22intellimirrorSCP%22%20OR%20ObjectClass=%22serviceAdministrationPoint%22)%20AND%20pszAttributeName%20=%20%22WhenCreated%22)%20%7C%20%20%20%20%20makemv%20pszLastOriginatingDsaDN%20delim=%22,CN=%22%20%7C%20eval%20OriginatingDC%20=%20mvindex(pszLastOriginatingDsaDN,%201,%201)%20%20%0A%7C%20%20search%20$click.name2$%20=%20%22$click.value2$%22&earliest=0&latest=
================================================ FILE: SA-ADTimeline/default/data/ui/views/getting_started.xml ================================================

Index

  1. Importing ADTimeline data in Splunk
  2. Source types and extracted fields
  3. AD General information dashboards
  4. AD threat hunting dashboards
  5. Enhance your traditional event logs threat hunting with ADTimeline

Importing ADTimeline data in Splunk

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. In order to be able to process this data with Splunk run the ADTimeline PowerShell script against your Active Directory domain as described on the project homepage.

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

You can import the data in an existing index with other source types (e.g. Windows event logs) or create a dedicated one. Navigate to the "add data" page and select "upload files from my computer":

Select the file you wish to upload: timeline_%DOMAINFQDN%.csv, ADobjects_%DOMAINFQDN%.xml or gcADobjects_%DOMAINFQDN%.xml:

Select the appropriate source type:

  • Adtimeline source type for the file timeline_%DOMAINFQDN%.csv
  • Adobjects source type for the file ADobjects_%DOMAINFQDN%.xml
  • Gcobjects source type for the file gcADobjects_%DOMAINFQDN%.xml if the file exists

The host field value should be the same for each file and match the Active Directory fully qualified domain name (%DOMAINFQDN%), after select the desired index:

Review your settings before import and repeat the above steps for each file generated by the ADTimeline script. If you ran the script against many Active Directory domains, repeat also the same steps, just change the host field value accordingly.

Source types and extracted fields

The adtimeline source type

The adtimeline source type 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 source type

The adobjects source type 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 source type

The gcobjects source type 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

Active Directory Infrastructure dashboard

This dashboard analyses Adtimeline data in order to create some panels giving you information on the Windows domain infrastructure. Select the appropriate Index and Active Directory domain you wish to analyze:

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.

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. Select the appropriate index and the Active Directory domain you wish to analyze:

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

Investigate timeframe dashboard

Use this dashboard to investigate a particular timeframe. Select the appropriate index, the Active Directory domain you wish to analyze and finally the timeframe you wish to investigate:

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 chart gives you stats about object lifetimes in hours and a second one figures by ObjectClass.
  • Objects added or removed from groups or ACL modifications within timeframe: This table focuses on the Member and nTSecurityDescriptor attributes, which can help detect an elevation of privilege for a specific account or a backdoor setup by the attacker, the DistinguishedName value of the member and the time the member was added or removed from the group is given in that table. Which makes it more detailed than the above AD Timeline panel. A chart displaying nTSecurityDescriptor modifications by ObjectClass and another displaying the number of times an object was added or removed from a group are given
  • GPOs modifications within timeframe: A GPO can used by an attacker in various ways, for example to inject malicious code in logon/startup scripts, deploy malware at scale with an immediate scheduled task, setup a backdoor by modifying the nTSecurityDescriptor... For each attribute modification this table gives you the current client side extensions of the GPO and where the object is linked (OU, site or domain root).

Track suspicious activity dashboard

This dashboard analyses the Active Directory timeline and highlights some modifications which can be a sign of a suspicious activity, the modifications spotted can also be legitimate and need a triage analysis. Select the appropriate index and the Active Directory domain you wish to analyze:

The different panels are:

  • ACL modifications: This panel does not replace a thorough analysis of the Active Directory permissions with tools such as AD Control Paths. The panel contains a graph displaying a weekly timeline of ACL modifications per ObjectClass which occured one year back, some tables are focusing on the domain root and AdminSDHolder objects where permissions can be used as backdoor by an attacker. Finally, some statistics by ObjectClass and by least frequent owners are displayed.
  • Accounts: This panel show account modifications which can a be sign of suspicious activity such as users added and removed from groups, some charts provide stats by number of times the account was added or removed, membership time in days, Organizational unit where accounts are located (an account from the "non_privileged_users" OU added and removed from a privileged group can be a sign of suspicious activity). There are some graphs, the first graph shows a timeline of accounts lockouts in order to highlight brute force attacks, the second graph shows SID history editions which can be suspicious outside a domain migration period, the next graph analyses all the different attributes modified on an account during a password change (supplementalCredentials, lmPwdHistory, unicodePwd...) and checks they are modified at the same time. A table displays resource based constrained delegation setup on privileged account or domain controller computer objects, which can be a backdoor setup by an attacker. Finally a chart displays domain controller computer objects password change frequency, an attacker could modify the DC registry to disable computer password change and use this password as a backdoor.
  • GPOs: A table of GPOs modifications having an audit client side extension is displayed, an attacker could change the audit settings on the domain to perform malicious actions with stealth. Finally modifications which could result in a GPO processing malfunctioning are displayed, this includes gPCFunctionalityVersion, gPCFileSysPath or versionNumber attribute modification.
  • DCshadow detection: The DCshadow is an attack which allows an attacker to push modifications in Active Directory and bypass traditional alerting by installing a fake DC. It was first presented by Vincent Le Toux and Benjamin Delpy at the BlueHat IL 2018 conference. The first graph will try to detect the installation of the fake DC by analyzing server and nTDSDSA ObjectClass. The two following tables will try to detect replication metadata tampering by analyzing usnOriginatingChange and usnLocalChange values which should increment through the time.
  • Schema and configuration partition suspicious modifications: The first graph displays Active Directory attribute modifications related to the configuration and schema partitions which can lower the security of the domain, used as backdoor by an attacker or hide information to the security team. The second graph is relevant if you have Exchange on premises and track modifications in the configuration partition which can be a sign of mail exfiltration.

Track suspicious Exchange activity dashboard

This dashboard analyses your Exchange onprem Active Directory objects and highlights some modifications which can be a sign of a suspicious activity, the modifications spotted can also be legitimate and need a triage analysis.

The different panels are:

  • Microsoft Exchange infrastructure:: Exchange version and servers.
  • Possible mail exfiltration: Mail forwarders setup on mailboxes, transport rules, remote domains, maibox export requests, content searches...
  • Persistence: RBAC roles and ACL modifications on Exchange objects.
  • MsExchangeSecurityGroups:: Timeline and group membership of builtin Exchange security groups.
  • Phishing::Modifications on transport rules related to SCL and disclaimer.

Enhance your traditional event logs threat hunting with ADTimeline

The adobjects sourcetype is a set of data which can be used to uncover suspicious activity by performing Active Directory educated queries on the Windows event logs. We assume the sourcetype used for event logs is called winevent and its EventData part has the correct field extraction applied (ex EventID 4624 has among other fields TargetUserName and TargetUserSid extracted):

You can perfrom similar queries with the Splunk App for Windows Infrastructure and the Splunk Supporting Add-on for Active Directory. Here are some queries using ADTimeline data and Windows event logs which can help with your threat hunt.

Statistics on privileged accounts logons:

index="*" sourcetype="winevent" EventID="4624" Channel="Security" 
[search index="*" sourcetype=adobjects  ((ObjectClass = "user" OR ObjectClass = "inetOrgPerson") AND adminCount=1) earliest = 1 latest = now() | rename SID as TargetUserSid | fields TargetUserSid] 
| strcat TargetDomainName "\\" TargetUserName TargetFullName | stats values(TargetFullName) as TargetFullName , values(LogonType) as logonTypes, values(IpAddress) as IpAdresses, values(Computer) as Computers, dc(Computer) as CountComputers, dc(IpAddress) as CountIpAdresses by TargetUserSid

Get processes running under a privileged account:
index="*" sourcetype="winevent" EventID="4688" Channel="Security" 
[search index="*" sourcetype=adobjects  ((ObjectClass = "user" OR ObjectClass = "inetOrgPerson") AND adminCount=1) earliest = 1 latest = now() | rename SamAccountName as TargetUserName | fields TargetUserName] 
OR [search index="*" sourcetype=adobjects  ((ObjectClass = "user" OR ObjectClass = "inetOrgPerson") AND adminCount=1) earliest = 1 latest = now() | rename SID as SubjectUserSid | fields SubjectUserSid] 
|  stats values(CommandLine) by Computer, TargetUserName,SubjectUserName
Get all privileged accounts PowerShell activity eventlogs:
index="*" sourcetype="winevent" Channel="*PowerShell*"  
[search index="*" sourcetype=adobjects  ((ObjectClass = "user" OR ObjectClass = "inetOrgPerson") AND adminCount=1) earliest = 1 latest = now() | dedup SamAccountName | return 1000 $SamAccountName]
Detect Kerberoasting possible activity:
index="*" sourcetype="winevent" Channel="Security" EventID="4769" 
[search index="*" sourcetype=adobjects (ObjectClass = "user" OR ObjectClass = "inetOrgPerson") AND (SPNs=* AND NOT Name=krbtgt) earliest = 1 latest = now() | rename SID as ServiceSid | fields ServiceSid] 
| strcat TargetDomainName "\\" TargetUserName TargetFullName  
|  eval time=strftime(_time,"%Y-%m-%d %H:%M:%S") 
|  stats list(ServiceName) as Services, distinct_count(ServiceName) as nbServices, list(time) as time by IpAddress, TicketEncryptionType 
| sort -nbServices
Detect abnormal processes running under Kerberoastable accounts:
index="*" sourcetype="winevent" Channel="Security" EventID="4688" 
[search index="*" sourcetype=adobjects  (ObjectClass = "user" OR ObjectClass = "inetOrgPerson") AND (SPNs=* AND NOT Name=krbtgt)  earliest = 1 latest = now()   | rename SamAccountName as TargetUserName | fields TargetUserName ] 
OR  [search index="*" sourcetype=adobjects  (ObjectClass = "user" OR ObjectClass = "inetOrgPerson") AND (SPNs=* AND NOT Name=krbtgt)  earliest = 1 latest = now()   | rename SID as SubjectUserSid | fields SubjectUserSid ] 
|  stats values(CommandLine) as cmdlines, values(TargetUserName) as TargetSubjectNames, values(SubjectUserName) as SubjectUserNames by Computer
Detect abnormal Kerberoastable user account logons:
index="*" sourcetype="winevent" Channel="Security" EventID="4624" 
[search index="*" sourcetype=adobjects   (ObjectClass = "user" OR ObjectClass = "inetOrgPerson") AND (SPNs=* AND NOT Name=krbtgt)  earliest = 1 latest = now() | rename SID as TargetUserSid  | fields TargetUserSid] 
| strcat TargetDomainName "\\" TargetUserName TargetFullName | stats values(TargetFullName) as TargetFullNames, values(IpAddress) as IpAddresses by LogonType, Computer
Detect abnormal AS-REP roastable user account logons:
index="*" sourcetype="winevent" Channel="Security" EventID="4624" 
[search index="*" sourcetype=adobjects (ObjectClass = "user" OR ObjectClass = "inetOrgPerson") earliest = 1 latest = now() |  eval eval_asrep_bit = floor(userAccountControl / pow(2, 22)) %2 | search eval_asrep_bit = 1 |  rename SID as TargetUserSid  | fields TargetUserSid]  
| strcat TargetDomainName "\\" TargetUserName TargetFullName | stats values(TargetFullName) as TargetFullNames, values(IpAddress) as IpAddresses by LogonType, Computer
Privileged accounts with flag "cannot be delegated" not set authenticating against computer configured for unconstrained delegation:
index="*" sourcetype="winevent" EventID="4624" Channel="Security" 
[search index="*" sourcetype=adobjects ObjectClass = "Computer" earliest = 1 latest = now() | eval eval_deleg_bit = floor(userAccountControl / pow(2, 19)) %2  | search  eval_deleg_bit = 1 | eval eval_dc_bit = floor(userAccountControl / pow(2, 13)) %2 |  eval eval_rodc_bit = floor(userAccountControl / pow(2, 26)) %2 | search eval_dc_bit = 0 AND eval_rodc_bit = 0 |   rename dNSHostName as Computer | fields Computer] 
|  search *   [search index="*" sourcetype=adobjects  ((ObjectClass = "user" OR ObjectClass = "inetOrgPerson") AND adminCount=1) earliest = 1 latest = now() | eval canbedelagated = round(((userAccountControl / pow(2, 20)) %2), 0) | search canbedelagated = 0 | rename SID as TargetUserSid  | fields TargetUserSid ] 
|  strcat TargetDomainName "\\" TargetUserName TargetFullName 
| table  _time, Computer, TargetFullName, IpAddress, LogonType, LogonProcessName
Detect possible printer bug triggering:
index="*" sourcetype="winevent" EventID="4624" Channel="Security" TargetUserName = "*$" NOT TargetUserSid="S-1-5-18"
[search index="*" sourcetype=adobjects ObjectClass = "Computer"  earliest = 1 latest = now() |  eval eval_deleg_bit = floor(userAccountControl / pow(2, 19)) %2  | search  eval_deleg_bit = 1 | eval eval_dc_bit = floor(userAccountControl / pow(2, 13)) %2 |  eval eval_rodc_bit = floor(userAccountControl / pow(2, 26)) %2 | search eval_dc_bit = 0 AND eval_rodc_bit = 0  |  rename dNSHostName as Computer | fields Computer]
| strcat TargetDomainName "\\" TargetUserName TargetFullName | stats values(LogonType), values(IpAddress), values(LogonProcessName) count by Computer, TargetFullName
================================================ FILE: SA-ADTimeline/default/data/ui/views/investigate_timeframe.xml ================================================
| tstats latest(_time) where index=* by index true index index | tstats latest(_time) where index=$ad_index$ (sourcetype=adobjects OR sourcetype=gcobjects OR sourcetype=adtimeline) by host true host host -7d@h now

AD Timeline: index=$ad_index$ host=$domain_host$ sourcetype=adtimeline NOT (pszAttributeName="Member" AND dwVersion = 0) | makemv pszLastOriginatingDsaDN delim=",CN=" | eval OriginatingDC = mvindex(pszLastOriginatingDsaDN, 1, 1) | table _time, DN, ObjectClass, pszAttributeName, dwVersion, OriginatingDC | sort -_time $time_token.earliest$ $time_token.latest$ {"whenCreated":#B6C75A,"isDeleted":#AF575A,"nTSecurityDescriptor":#F1813F,"member":#F1813F} search?q=index=$ad_index$%20host=$domain_host$%20sourcetype=adtimeline%20%7C%20makemv%20pszLastOriginatingDsaDN%20delim=%22,CN=%22%20%7C%20eval%20OriginatingDC%20=%20mvindex(pszLastOriginatingDsaDN,%201,%201)%20%7C%20%20search%20$click.name2$%20=%20%22$click.value2$%22&earliest=$time_token.earliest$&latest=$time_token.latest$
Global stats (1/2): Modifications by ObjectClass index=$ad_index$ host=$domain_host$ sourcetype=adtimeline NOT ObjectClass="System.DirectoryServices.ResultPropertyValueCollection" | stats count by ObjectClass $time_token.earliest$ $time_token.latest$ search?q=index=$ad_index$%20host=$domain_host$%20sourcetype=adtimeline%20NOT%20ObjectClass=%22System.DirectoryServices.ResultPropertyValueCollection%22%20%7C%20search%20$click.name$%20=%20%22$click.value$%22&earliest=$time_token.earliest$&latest=$time_token.latest$ Modifications by pszAttributeName: index=$ad_index$ host=$domain_host$ sourcetype=adtimeline | stats count by pszAttributeName $time_token.earliest$ $time_token.latest$ search?q=index=$ad_index$%20host=$domain_host$%20sourcetype=adtimeline%20%20%7C%20search%20$click.name$%20=%20%22$click.value$%22&earliest=$time_token.earliest$&latest=$time_token.latest$ Deletions by ObjectClass: index=$ad_index$ host=$domain_host$ sourcetype=adtimeline pszAttributeName="isDeleted" NOT ObjectClass="System.DirectoryServices.ResultPropertyValueCollection" | stats count by ObjectClass $time_token.earliest$ $time_token.latest$ toto search?q=index=$ad_index$%20host=$domain_host$%20sourcetype=adtimeline%20pszAttributeName=%22isDeleted%22%20%20NOT%20ObjectClass=%22System.DirectoryServices.ResultPropertyValueCollection%22%20%7C%20search%20$click.name$%20=%20%22$click.value$%22&earliest=$time_token.earliest$&latest=$time_token.latest$

Deletions by ObjectClass: No results

Global stats (2/2): ObjectClass modifications by day of the week: index=$ad_index$ host=$domain_host$ sourcetype=adtimeline NOT ObjectClass="System.DirectoryServices.ResultPropertyValueCollection" | chart count over date_wday by ObjectClass $time_token.earliest$ $time_token.latest$ search?q=index=$ad_index$%20host=$domain_host$%20sourcetype=adtimeline%20NOT%20ObjectClass=%22System.DirectoryServices.ResultPropertyValueCollection%22%20%7C%20search%20$click.name$%20=%20%22$click.value$%22%20AND%20ObjectClass%20=%20%22$click.name2$%22&earliest=$time_token.earliest$&latest=$time_token.latest$ ObjectClass modifications by hour: index=$ad_index$ host=$domain_host$ sourcetype=adtimeline NOT ObjectClass="System.DirectoryServices.ResultPropertyValueCollection" | chart count over date_hour by ObjectClass $time_token.earliest$ $time_token.latest$ search?q=index=$ad_index$%20host=$domain_host$%20sourcetype=adtimeline%20NOT%20ObjectClass=%22System.DirectoryServices.ResultPropertyValueCollection%22%20%7C%20search%20$click.name$%20=%20%22$click.value$%22%20AND%20ObjectClass%20=%20%22$click.name2$%22&earliest=$time_token.earliest$&latest=$time_token.latest$ Modifications by Originating DC: index=$ad_index$ host=$domain_host$ sourcetype=adtimeline | makemv pszLastOriginatingDsaDN delim=",CN=" | eval OriginatingDC = mvindex(pszLastOriginatingDsaDN, 1, 1) | stats count by OriginatingDC $time_token.earliest$ $time_token.latest$ search?q=index=$ad_index$%20host=$domain_host$%20sourcetype=adtimeline%20%7C%20makemv%20pszLastOriginatingDsaDN%20delim=%22,CN=%22%20%7C%20eval%20OriginatingDC%20=%20mvindex(pszLastOriginatingDsaDN,%201,%201)%20%7C%20search%20$click.name$%20=%20%22$click.value$%22&earliest=$time_token.earliest$&latest=$time_token.latest$
Items created and deleted within timeframe:

MITRE | ATT&CK T1136, T1531

Timeline: toto index=$ad_index$ host=$domain_host$ sourcetype=adtimeline (pszAttributeName="isDeleted" OR pszAttributeName="WhenCreated")| makemv pszLastOriginatingDsaDN delim=",CN=" | eval OriginatingDC = mvindex(pszLastOriginatingDsaDN, 1, 1) | stats count, values(ObjectClass) as ObjectClass, list(ftimeLastOriginatingChange) as Whencreated_deleted, list(OriginatingDC) as OriginatingDCs by DN | where count > 1 | table DN, ObjectClass, Whencreated_deleted, OriginatingDCs $time_token.earliest$ $time_token.latest$ search?q=index=$ad_index$%20host=$domain_host$%20sourcetype=adtimeline%20(pszAttributeName=%22isDeleted%22%20OR%20pszAttributeName=%22WhenCreated%22)%7C%20makemv%20pszLastOriginatingDsaDN%20delim=%22,CN=%22%20%7C%20eval%20OriginatingDC%20=%20mvindex(pszLastOriginatingDsaDN,%201,%201)%20%7C%20stats%20count,%20values(ObjectClass)%20as%20ObjectClass,%20list(ftimeLastOriginatingChange)%20as%20Whencreated_deleted,%20list(OriginatingDC)%20as%20OriginatingDCs%20by%20DN%20%7C%20where%20count%20%3E%201%20%7C%20search%20$click.name2$%20=%20%22$click.value2$%22&earliest=$time_token.earliest$&latest=$time_token.latest$

Items created and deleted within timeframe: No results

Object lifetime in hours: toto index=$ad_index$ host=$domain_host$ sourcetype=adtimeline (pszAttributeName="isDeleted" OR pszAttributeName="WhenCreated")| makemv pszLastOriginatingDsaDN delim=",CN=" | eval OriginatingDC = mvindex(pszLastOriginatingDsaDN, 1, 1) | stats count, list(ftimeLastOriginatingChange) as temps, list(OriginatingDC) as OriginatingDCs by DN | where count > 1 | eval deltime = strptime(mvindex(temps,0),"%Y-%m-%dT%H:%M:%S%Z") | eval createtime = strptime(mvindex(temps,1),"%Y-%m-%dT%H:%M:%S%Z") | eval Lifetime_hours=abs(floor((deltime-createtime)/3600)) | stats count by Lifetime_hours $time_token.earliest$ $time_token.latest$ search?q=index=$ad_index$%20host=$domain_host$%20sourcetype=adtimeline%20(pszAttributeName%3D%22isDeleted%22%20OR%20pszAttributeName%3D%22WhenCreated%22)%7C%20makemv%20pszLastOriginatingDsaDN%20delim%3D%22%2CCN%3D%22%20%7C%20eval%20OriginatingDC%20%3D%20mvindex(pszLastOriginatingDsaDN%2C%201%2C%201)%20%7C%20stats%20count%2C%20list(ftimeLastOriginatingChange)%20as%20temps%2C%20list(OriginatingDC)%20as%20OriginatingDCs%2C%20values(ObjectClass)%20as%20ObjectClass%20by%20DN%20%7C%20where%20count%20%3E%201%20%7C%20eval%20deltime%20%3D%20strptime(mvindex(temps%2C0)%2C%22%2525Y-%2525m-%2525dT%2525H%3A%2525M%3A%2525S%2525Z%22)%20%7C%20eval%20createtime%20%3D%20strptime(mvindex(temps%2C1)%2C%22%2525Y-%2525m-%2525dT%2525H%3A%2525M%3A%2525S%2525Z%22)%20%7C%20eval%20Lifetime_hours%3Dabs(floor((deltime-createtime)%2F3600))%20%7C%20search%20Lifetime_hours%20%3D%20%22$click.value$%22%20%0A%7C%20table%20DN%2CObjectClass%2Ctemps%2CLifetime_hours%2C%20OriginatingDCs&earliest=$time_token.earliest$&latest=$time_token.latest$

Object lifetime in hours: No results

Items created and deleted within timeframe by ObjectClass: toto index=$ad_index$ host=$domain_host$ sourcetype=adtimeline (pszAttributeName="isDeleted" OR pszAttributeName="WhenCreated") NOT ObjectClass="System.DirectoryServices.ResultPropertyValueCollection" | makemv pszLastOriginatingDsaDN delim=",CN=" | eval OriginatingDC = mvindex(pszLastOriginatingDsaDN, 1, 1) | stats count, list(ftimeLastOriginatingChange) as temps, values(ObjectClass) as ObjectClass list(OriginatingDC) as OriginatingDCs by DN | where count > 1 | stats count by ObjectClass $time_token.earliest$ $time_token.latest$ search?q=index=$ad_index$%20host=$domain_host$%20sourcetype=adtimeline%20(pszAttributeName=%22isDeleted%22%20OR%20pszAttributeName=%22WhenCreated%22)%20NOT%20ObjectClass=%22System.DirectoryServices.ResultPropertyValueCollection%22%20%7C%20makemv%20pszLastOriginatingDsaDN%20delim=%22,CN=%22%20%7C%20eval%20OriginatingDC%20=%20mvindex(pszLastOriginatingDsaDN,%201,%201)%20%7C%20stats%20count,%20list(ftimeLastOriginatingChange)%20as%20temps,%20values(ObjectClass)%20as%20ObjectClass%20list(OriginatingDC)%20as%20OriginatingDCs%20by%20DN%20%7C%20where%20count%20%3E%201%20%7C%20%20search%20$click.name$%20=%20%22$click.value$%22%20%0A%7C%20table%20DN,ObjectClass,temps,%20OriginatingDCs&earliest=$time_token.earliest$&latest=$time_token.latest$

Items created and deleted within timeframe by ObjectClass: No results

Objects added or removed from groups or ACL modifications within timeframe:

MITRE | ATT&CK T1098, T1531

Timeline: toto index=$ad_index$ host=$domain_host$ sourcetype=adtimeline (pszAttributeName="Member" AND dwVersion != 0) OR (pszAttributeName="nTSecurityDescriptor" AND dwVersion >= 2) | makemv pszLastOriginatingDsaDN delim=",CN=" | eval OriginatingDC = mvindex(pszLastOriginatingDsaDN, 1, 1) | table _time, DN, pszAttributeName, Member, dwVersion, OriginatingDC,ftimeCreated , ftimeDeleted | sort -_time $time_token.earliest$ $time_token.latest$ search?q=index=$ad_index$%20host=$domain_host$%20sourcetype=adtimeline%20(pszAttributeName=%22Member%22%20AND%20dwVersion%20!=%200)%20OR%20(pszAttributeName=%22nTSecurityDescriptor%22%20%20AND%20dwVersion%20%3E=%202)%20%7C%20makemv%20pszLastOriginatingDsaDN%20delim=%22,CN=%22%20%7C%20eval%20OriginatingDC%20=%20mvindex(pszLastOriginatingDsaDN,%201,%201)%20%7C%20search%20$click.name2$%20=%20%22$click.value2$%22&earliest=$time_token.earliest$&latest=$time_token.latest$

Timeline: No results

ACL modifications by ObjectClass: index=$ad_index$ host=$domain_host$ sourcetype=adtimeline (pszAttributeName="nTSecurityDescriptor" AND dwVersion >= 2) NOT ObjectClass="System.DirectoryServices.ResultPropertyValueCollection" | makemv pszLastOriginatingDsaDN delim=",CN=" | eval OriginatingDC = mvindex(pszLastOriginatingDsaDN, 1, 1) | stats count by ObjectClass $time_token.earliest$ $time_token.latest$ toto search?q=index=$ad_index$%20host=$domain_host$%20sourcetype=adtimeline%20%20(pszAttributeName=%22nTSecurityDescriptor%22%20%20AND%20dwVersion%20%3E=%202)%20NOT%20ObjectClass=%22System.DirectoryServices.ResultPropertyValueCollection%22%20%7C%20makemv%20pszLastOriginatingDsaDN%20delim=%22,CN=%22%20%7C%20eval%20OriginatingDC%20=%20mvindex(pszLastOriginatingDsaDN,%201,%201)%20%7C%20search%20$click.name$%20=%20%22$click.value$%22&earliest=$time_token.earliest$&latest=$time_token.latest$

ACL modifications by ObjectClass: No results

Group membership modification by dwVersion: toto index=$ad_index$ host=$domain_host$ sourcetype=adtimeline (pszAttributeName="Member" AND dwVersion != 0) | makemv pszLastOriginatingDsaDN delim=",CN=" | eval OriginatingDC = mvindex(pszLastOriginatingDsaDN, 1, 1) | stats count by dwVersion $time_token.earliest$ $time_token.latest$ search?q=index=$ad_index$%20host=$domain_host$%20sourcetype=adtimeline%20(pszAttributeName=%22Member%22%20AND%20dwVersion%20!=%200)%20%20%7C%20makemv%20pszLastOriginatingDsaDN%20delim=%22,CN=%22%20%7C%20eval%20OriginatingDC%20=%20mvindex(pszLastOriginatingDsaDN,%201,%201)%20%7C%20search%20$click.name$%20=%20%22$click.value$%22&earliest=$time_token.earliest$&latest=$time_token.latest$

Group membership modification by dwVersion: No results

GPOs modifications within timeframe:

MITRE | ATT&CK T1484

Timeline: index=$ad_index$ host=$domain_host$ sourcetype=adtimeline ObjectClass=groupPolicyContainer | join DN [search index=$ad_index$ host=$domain_host$ sourcetype="adobjects" ObjectClass=groupPolicyContainer earliest = 1 latest = now() | rex field=_raw "gPCMachineExtensionNames\">(?<gPCMachineExtensionNames>.+?)</S>" | rex field=_raw "gPCUserExtensionNames\">(?<gPCUserExtensionNames>.+?)</S>" | rex field=gPCMachineExtensionNames "\[(?<MachineCSEs>\{.+?\})\]?" max_match=0 | rex field=gPCUserExtensionNames "\[(?<UserCSEs>\{.+?\})\]?" max_match=0 | eval AllCSEs=coalesce(MachineCSEs,UserCSEs) | dedup AllCSEs | lookup CSE_lookup GUID AS AllCSEs OUTPUTNEW CSE as ClientSideExtensions | fields DN, DisplayName, ClientSideExtensions] | join Name [search index=$ad_index$ host=$domain_host$ sourcetype="adobjects" (ObjectClass = "domainDNS" OR ObjectClass = "site" OR ObjectClass = "organizationalUnit") earliest = 1 latest = now() | rex field=_raw "gPLink\">(?<gPLink>.+?)</S>" | search gPLink = "*" | rex field=gPLink "(CN|cn)\=(?<Name>\{.+?\})," max_match=0 | mvexpand Name | stats values(DN) as gPLinks by Name | fields Name, gPLinks ] | makemv pszLastOriginatingDsaDN delim=",CN=" | eval OriginatingDC = mvindex(pszLastOriginatingDsaDN, 1, 1) | table _time, DisplayName, pszAttributeName, dwVersion, ClientSideExtensions, gPLinks, Name, OriginatingDC | sort -_time $time_token.earliest$ $time_token.latest$ toto {"isDeleted":#AF575A,"whenCreated":#B6C75A} search?q=index=$ad_index$%20host=$domain_host$%20sourcetype=adtimeline%20ObjectClass=groupPolicyContainer%20%7C%20join%20DN%20%5Bsearch%20index=$ad_index$%20host=$domain_host$%20sourcetype=%22adobjects%22%20ObjectClass=groupPolicyContainer%20earliest%20=%201%20latest%20=%20now()%20%20%7C%20rex%20field=_raw%20%22gPCMachineExtensionNames%5C%22%3E(%3F%3CgPCMachineExtensionNames%3E.%2B%3F)%3C/S%3E%22%20%0A%7C%20rex%20field=_raw%20%22gPCUserExtensionNames%5C%22%3E(%3F%3CgPCUserExtensionNames%3E.%2B%3F)%3C/S%3E%22%20%0A%7C%20rex%20field=gPCMachineExtensionNames%20%22%5C%5B(%3F%3CMachineCSEs%3E%5C%7B.%2B%3F%5C%7D)%5C%5D%3F%22%20max_match=0%20%7C%20rex%20field=gPCUserExtensionNames%20%22%5C%5B(%3F%3CUserCSEs%3E%5C%7B.%2B%3F%5C%7D)%5C%5D%3F%22%20max_match=0%20%0A%7C%20eval%20AllCSEs=coalesce(MachineCSEs,UserCSEs)%20%0A%7C%20%20dedup%20AllCSEs%20%0A%7C%20%20lookup%20CSE_lookup%20GUID%20AS%20AllCSEs%20OUTPUTNEW%20CSE%20as%20ClientSideExtensions%20%7C%20fields%20DN,%20DisplayName,%20ClientSideExtensions%5D%20%0A%7C%20%20join%20Name%20%0A%20%20%20%20%5Bsearch%20index=$ad_index$%20host=$domain_host$%20sourcetype=%22adobjects%22%20(ObjectClass%20=%20%22domainDNS%22%20OR%20ObjectClass%20=%20%22site%22%20OR%20ObjectClass%20=%20%22organizationalUnit%22)%20earliest%20=%201%20latest%20=%20now()%20%7C%20rex%20field=_raw%20%22gPLink%5C%22%3E(%3F%3CgPLink%3E.%2B%3F)%3C/S%3E%22%20%0A%20%7C%20%20search%20%20gPLink%20=%20%22*%22%20%0A%7C%20%20rex%20field=gPLink%20%22(CN%7Ccn)%5C=(%3F%3CName%3E%5C%7B.%2B%3F%5C%7D),%22%20max_match=0%20%0A%7C%20mvexpand%20Name%0A%7C%20%20stats%20values(DN)%20as%20gPLinks%20by%20Name%20%0A%7C%20%20fields%20Name,%20gPLinks%20%5D%20%7C%20makemv%20pszLastOriginatingDsaDN%20delim=%22,CN=%22%20%7C%20eval%20OriginatingDC%20=%20mvindex(pszLastOriginatingDsaDN,%201,%201)%20%7C%20search%20$click.name2$%20=%20%22$click.value2$%22&earliest=$time_token.earliest$&latest=$time_token.latest$

Timeline: No results

© 2020 The MITRE Corporation. This work is reproduced and distributed with the permission of The MITRE Corporation.

================================================ FILE: SA-ADTimeline/default/data/ui/views/sensitive_accounts.xml ================================================
| tstats latest(_time) where index=* by index true index index | tstats latest(_time) where index=$ad_index$ (sourcetype=adobjects OR sourcetype=gcobjects OR sourcetype=adtimeline) by host true host host

Admin accounts: Inventory, adminCount attribute: index=$ad_index$ host=$domain_host$ sourcetype=adobjects (ObjectClass = "user" OR ObjectClass = "inetOrgPerson" OR ObjectClass = "Computer") AND (adminCount=1 NOT Name="krbtgt") | eval Status = if((userAccountControl%4)>=2,"disabled","enabled") | eval SmartCard = if(round (((userAccountControl / pow(2, 18)) %2), 0) == 1,"required","not required") | eval be_delegated = if(round(((userAccountControl / pow(2, 20)) %2), 0) == 1,"cannot","can") | eval lastlogon_timestamp = strftime(lastLogonTimestamp/10000000 - 11644473600, "%Y-%m-%dT%H:%M:%S") | table DN, Status, be_delegated, SmartCard, lastlogon_timestamp, whenCreated | sort -lastlogon_timestamp 0 {"can":#D98491,"cannot":#A1D379} {"not required":#D98491,"required":#A1D379} {"enabled":#A1D379,"disabled":#F8BE34} search?q=index=$ad_index$%20host=$domain_host$%20sourcetype=adobjects%20%20(ObjectClass%20=%20%22user%22%20OR%20ObjectClass%20=%20%22inetOrgPerson%22%20OR%20ObjectClass%20=%20%22Computer%22)%20AND%20(adminCount=1%20NOT%20Name=%22krbtgt%22)%20%7C%20%20eval%20Status%20=%20if((userAccountControl%254)%3E=2,%22disabled%22,%22enabled%22)%20%20%7C%20eval%20SmartCard%20=%20if(round%20(((userAccountControl%20/%20pow(2,%2018))%20%252),%200)%20==%201,%22required%22,%22not%20required%22)%20%20%7C%20eval%20be_delegated%20=%20if(round(((userAccountControl%20/%20pow(2,%2020))%20%252),%200)%20==%201,%22cannot%22,%22can%22)%20%7C%20eval%20lastlogon_timestamp%20=%20strftime(lastLogonTimestamp/10000000%20-%2011644473600,%20%22%25Y-%25m-%25dT%25H:%25M:%25S%22)%20%7C%20search%20$click.name2$%20=%20%22$click.value2$%22&earliest=0&latest=
Timeline, adminCount attribute: index=$ad_index$ host=$domain_host$ sourcetype=adtimeline (pszAttributeName = adminCount OR pszAttributeName = isDeleted OR (pszAttributeName = member AND dwVersion != 0) OR pszAttributeName = userAccountControl OR pszAttributeName = whenCreated) [search index=$ad_index$ host=$domain_host$ sourcetype=adobjects (ObjectClass = "user" OR ObjectClass = "inetOrgPerson" OR ObjectClass = "group") AND adminCount=1 | table DN] | table _time, DN, pszAttributeName, Member, dwVersion, ftimeCreated, ftimeDeleted | sort -_time 0 {"whenCreated":#53A051,"isDeleted":#DC4E41,"member":#006D9C,"adminCount":#EC9960,"userAccountControl":#62B3B2} search?q=index=$ad_index$%20host=$domain_host$%20sourcetype=adtimeline%20%20%5Bsearch%20index=$ad_index$%20host=$domain_host$%20sourcetype=adobjects%20%20(ObjectClass%20=%20%22user%22%20OR%20ObjectClass%20=%20%22inetOrgPerson%22%20OR%20ObjectClass%20=%20%22group%22)%20AND%20adminCount=1%20%7C%20table%20DN%5D%20%7C%20search%20$click.name2$%20=%20%22$click.value2$%22&earliest=0&latest=
Accounts sensitive to Kerberoast attacks: Ratio of kerberoastable accounts being privileged in the domain, SPN and adminCount attributes: index=$ad_index$ host=$domain_host$ sourcetype=adobjects (ObjectClass = "user" OR ObjectClass = "inetOrgPerson") AND ( SPNs = "*" AND NOT Name=krbtgt) | eval SPN = replace(SPNs, "(<(.|)S>|[\\n\r])" , "") | fillnull value="notset" adminCount | stats count as "Admincount ratio for users with SPN" by adminCount $earliest$ $latest$ toto search?q=index=$ad_index$%20host=$domain_host$%20sourcetype=adobjects%20%20%20(ObjectClass%20=%20%22user%22%20OR%20ObjectClass%20=%20%22inetOrgPerson%22)%20%20AND%20%20(%20SPNs%20=%20%22*%22%20AND%20NOT%20Name=krbtgt)%20%7C%20eval%20SPN%20=%20replace(SPNs,%20%22(%3C(.%7C)S%3E%7C%5B%5C%5Cn%5C%5Cr%5D)%22%20,%20%22%22)%20%20%7C%20fillnull%20value=%22notset%22%20adminCount%20%7C%20%20search%20$click.name$%20=%20%22$click.value$%22&earliest=$earliest$&latest=$latest$

Ratio of kerberoastable accounts being privileged in the domain, SPN and adminCount attributes: No results

Kerberoastable accounts inventory: toto index=$ad_index$ host=$domain_host$ sourcetype=adobjects (ObjectClass = "user" OR ObjectClass = "inetOrgPerson") AND (SPNs = "*" AND NOT Name= "krbtgt") | eval SPN = replace(SPNs, "(<(.|)S>|[\\n\r])" , "") | fillnull value="notset" adminCount | eval Status = if((userAccountControl%4)>=2,"disabled","enabled") | eval lastlogon_timestamp = strftime(lastLogonTimestamp/10000000 - 11644473600, "%Y-%m-%dT%H:%M:%S") | table DN, SPN, Status, adminCount, SID, lastlogon_timestamp, whenCreated | sort -lastlogon_timestamp 0 {"0":#A1D379,"1":#D98491,"notset":#A1D379} {"enabled":#A1D379,"disabled":#F8BE34} search?q=index=$ad_index$%20host=$domain_host$%20sourcetype=adobjects%20%20(ObjectClass%20=%20%22user%22%20OR%20ObjectClass%20=%20%22inetOrgPerson%22)%20AND%20(SPNs%20=%20%22*%22%20AND%20NOT%20Name=%20%22krbtgt%22)%20%7C%20eval%20SPN%20=%20replace(SPNs,%20%22(%3C(.%7C)S%3E%7C%5B%5C%5Cn%5C%5Cr%5D)%22%20,%20%22%22)%20%7C%20fillnull%20value=%22notset%22%20adminCount%20%7C%20eval%20Status%20=%20if((userAccountControl%254)%3E=2,%22disabled%22,%22enabled%22)%20%20%7C%20eval%20lastlogon_timestamp%20=%20strftime(lastLogonTimestamp/10000000%20-%2011644473600,%20%22%25Y-%25m-%25dT%25H:%25M:%25S%22)%20%7C%20search%20$click.name2$%20=%20%22$click.value2$%22&earliest=0&latest=

Kerberoastable accounts inventory: No results

Sensitive default accounts: Administrator account (RID 500): index=$ad_index$ host=$domain_host$ sourcetype=adobjects [search index=$ad_index$ host=$domain_host$ sourcetype=adobjects ObjectClass = "DomainDNS" | strcat SID "-500" SID | table SID] | eval Status = if((userAccountControl%4)>=2,"Administrator account is disabled","Administrator account is enabled") | table Status $earliest$ $latest$ search?q=index=$ad_index$%20host=$domain_host$%20%20(sourcetype=adobjects%20%20OR%20sourcetype=adtimeline)%20%5Bsearch%20index=$ad_index$%20host=$domain_host$%20sourcetype=adobjects%20%20ObjectClass%20=%20%22DomainDNS%22%20%7C%20strcat%20SID%20%22-500%22%20SID%20%7C%20table%20SID%5D&earliest=$earliest$&latest=$latest$ ]]> index=$ad_index$ host=$domain_host$ sourcetype=adtimeline pszAttributeName=SamAccountName [search index=$ad_index$ host=$domain_host$ sourcetype=adobjects ObjectClass = "DomainDNS" | strcat SID "-500" SID | table SID] | eval checkRenameAdmin =case(dwVersion >= 2, "Administrator account was renamed", 1=1 , "Administrator account was not renamed") | table checkRenameAdmin $earliest$ $latest$ index=$ad_index$ host=$domain_host$ sourcetype=adtimeline (pszAttributeName=pwdLastSet OR pszAttributeName=SamAccountName OR pszAttributeName=userAccountControl OR pszAttributeName=lockoutTime OR pszAttributeName=LastlogonTimestamp) [search index=$ad_index$ host=$domain_host$ sourcetype=adobjects ObjectClass = "DomainDNS" | strcat SID "-500" SID | table SID] | makemv pszLastOriginatingDsaDN delim=",CN=" | eval OriginatingDC = mvindex(pszLastOriginatingDsaDN, 1, 1) | table _time, Name, pszAttributeName, dwVersion, OriginatingDC | sort -_time 0 search?q=index=$ad_index$%20host=$domain_host$%20sourcetype=adtimeline%20(pszAttributeName=pwdLastSet%20OR%20pszAttributeName=SamAccountName%20OR%20pszAttributeName=userAccountControl%20OR%20pszAttributeName=lockoutTime%20OR%20pszAttributeName=LastlogonTimestamp)%20%20%5Bsearch%20index=$ad_index$%20host=$domain_host$%20sourcetype=adobjects%20%20ObjectClass%20=%20%22DomainDNS%22%20%7C%20strcat%20SID%20%22-500%22%20SID%20%7C%20table%20SID%5D%20%7C%20%20makemv%20pszLastOriginatingDsaDN%20delim=%22,CN=%22%20%7C%20eval%20OriginatingDC%20=%20mvindex(pszLastOriginatingDsaDN,%201,%201)&earliest=0&latest=
Guest account (RID 501): index=$ad_index$ host=$domain_host$ sourcetype=adobjects [search index=$ad_index$ host=$domain_host$ sourcetype=adobjects ObjectClass = "DomainDNS" | strcat SID "-501" SID | table SID] | eval UACmodulo4 = (userAccountControl%4) | eval Status = if( UACmodulo4 >=2,"Guest account is disabled","Guest account is enabled") | stats by Status, UACmodulo4 | rangemap field=UACmodulo4 severe=0-1 default=low $earliest$ $latest$ search?q=index=$ad_index$%20host=$domain_host$%20%20(sourcetype=adobjects%20OR%20sourcetype=adtimeline)%20%5Bsearch%20index=$ad_index$%20host=$domain_host$%20sourcetype=adobjects%20%20ObjectClass%20=%20%22DomainDNS%22%20%7C%20strcat%20SID%20%22-501%22%20SID%20%7C%20table%20SID%5D&earliest=$earliest$&latest=$latest$ index=$ad_index$ host=$domain_host$ sourcetype=adtimeline (pszAttributeName=pwdLastSet OR pszAttributeName=SamAccountName OR pszAttributeName=userAccountControl OR pszAttributeName=LastlogonTimestamp) [search index=$ad_index$ host=$domain_host$ sourcetype=adobjects ObjectClass = "DomainDNS" | strcat SID "-501" SID | table SID] | makemv pszLastOriginatingDsaDN delim=",CN=" | eval OriginatingDC = mvindex(pszLastOriginatingDsaDN, 1, 1) | table _time, Name, pszAttributeName, dwVersion, OriginatingDC | sort -_time 0 search?q=index=$ad_index$%20host=$domain_host$%20sourcetype=adtimeline%20(pszAttributeName=pwdLastSet%20OR%20pszAttributeName=SamAccountName%20OR%20pszAttributeName=userAccountControl%20OR%20pszAttributeName=LastlogonTimestamp)%20%20%5Bsearch%20index=$ad_index$%20host=$domain_host$%20sourcetype=adobjects%20%20ObjectClass%20=%20%22DomainDNS%22%20%7C%20strcat%20SID%20%22-501%22%20SID%20%7C%20table%20SID%5D%20%7C%20%20makemv%20pszLastOriginatingDsaDN%20delim=%22,CN=%22%20%7C%20eval%20OriginatingDC%20=%20mvindex(pszLastOriginatingDsaDN,%201,%201)&earliest=0&latest=
]]> Krbtgt account: index=$ad_index$ host=$domain_host$ sourcetype=adtimeline pszAttributeName=pwdLastSet [search index=$ad_index$ host=$domain_host$ sourcetype=adobjects ObjectClass = "DomainDNS" | strcat SID "-502" SID | table SID] | stats min(_time) as mintime, values(dwVersion) as version | eval diff = (now() - mintime) / 86400 | eval freq = diff / version | eval frequency=case(freq >= 730, "Krbtgt password is changed in average less than every two years", freq >= 365 , "Krbtgt password is changed in average less than every one year", 1=1, "Krbtgt password is changed in average at least every year") | stats count by frequency, freq | rangemap field=freq low=1-364 elevated=365-729 default=severe $earliest$ $latest$ search?q=index=$ad_index$%20host=$domain_host$%20%20(sourcetype=adobjects%20OR%20sourcetype=adtimeline)%20%5Bsearch%20index=$ad_index$%20host=$domain_host$%20sourcetype=adobjects%20%20ObjectClass%20=%20%22DomainDNS%22%20%7C%20strcat%20SID%20%22-502%22%20SID%20%7C%20table%20SID%5D&earliest=$earliest$&latest=$latest$ index=$ad_index$ host=$domain_host$ sourcetype=adtimeline pszAttributeName=pwdLastSet [search index=$ad_index$ host=$domain_host$ sourcetype=adobjects ObjectClass = "DomainDNS" | strcat SID "-502" SID | table SID] | makemv pszLastOriginatingDsaDN delim=",CN=" | eval OriginatingDC = mvindex(pszLastOriginatingDsaDN, 1, 1) | table _time, Name, pszAttributeName, dwVersion, OriginatingDC 0 {"1":#DC4E41,"2":#DC4E41,"3":#DC4E41} search?q=index=$ad_index$%20host=$domain_host$%20sourcetype=adtimeline%20pszAttributeName=pwdLastSet%20%20%5Bsearch%20index=$ad_index$%20host=$domain_host$%20sourcetype=adobjects%20%20ObjectClass%20=%20%22DomainDNS%22%20%7C%20strcat%20SID%20%22-502%22%20SID%20%7C%20table%20SID%5D%20%7C%20%20makemv%20pszLastOriginatingDsaDN%20delim=%22,CN=%22%20%7C%20eval%20OriginatingDC%20=%20mvindex(pszLastOriginatingDsaDN,%201,%201)&earliest=0&latest=
Accounts sensitive to AS-REP Roast attacks: Ratio of AS-REProastable accounts being privileged in the domain, userAccountControl and adminCount attributes: index=$ad_index$ host=$domain_host$ sourcetype=adobjects (ObjectClass = "user" OR ObjectClass = "inetOrgPerson") | eval eval_asrep_bit = floor(userAccountControl / pow(2, 22)) %2 | search eval_asrep_bit = 1 | fillnull value="notset" adminCount | stats count as "Admincount ratio for users with DONT_REQ_PREAUTH flag" by adminCount $earliest$ $latest$ toto search?q=index=$ad_index$%20host=$domain_host$%20sourcetype=adobjects%20%20(ObjectClass%20=%20%22user%22%20OR%20ObjectClass%20=%20%22inetOrgPerson%22)%20%20%7C%20%20eval%20eval_asrep_bit%20=%20floor(userAccountControl%20/%20pow(2,%2022))%20%252%20%7C%20search%20eval_asrep_bit%20=%201%20%20%7C%20fillnull%20value=%22notset%22%20adminCount%20%20%7C%20search%20$click.name$%20=%20%22$click.value$%22&earliest=$earliest$&latest=$latest$

Ratio of AS-REProastable accounts being privileged in the domain, userAccountControl and adminCount attributes: No results

AS-REP Roast accounts inventory: toto index=$ad_index$ host=$domain_host$ sourcetype=adobjects (ObjectClass = "user" OR ObjectClass = "inetOrgPerson") | eval eval_asrep_bit = floor(userAccountControl / pow(2, 22)) %2 | search eval_asrep_bit = 1 | fillnull value="notset" adminCount | eval status = if((userAccountControl%4)>=2,"disabled","enabled") | eval lastlogon_timestamp = strftime(lastLogonTimestamp/10000000 - 11644473600, "%Y-%m-%dT%H:%M:%S") | table DN, status, adminCount, lastlogon_timestamp, whenCreated | sort -lastlogon_timestamp 0 {"0":#A1D379,"1":#D98491,"notset":#A1D379} {"enabled":#A1D379,"disabled":#F8BE34} search?q=index=$ad_index$%20host=$domain_host$%20sourcetype=adobjects%20%20(ObjectClass%20=%20%22user%22%20OR%20ObjectClass%20=%20%22inetOrgPerson%22)%20%20%20%7C%20%20eval%20eval_asrep_bit%20=%20floor(userAccountControl%20/%20pow(2,%2022))%20%252%20%7C%20search%20eval_asrep_bit%20=%201%20%20%7C%20fillnull%20value=%22notset%22%20adminCount%20%20%7C%20eval%20status%20=%20if((userAccountControl%254)%3E=2,%22disabled%22,%22enabled%22)%20%20%7C%20eval%20lastlogon_timestamp%20=%20strftime(lastLogonTimestamp/10000000%20-%2011644473600,%20%22%25Y-%25m-%25dT%25H:%25M:%25S%22)%20%0A%7C%20search%20$click.name2$%20=%20%22$click.value2$%22&earliest=0&latest=

AS-REP Roast accounts inventory: No results

Kerberos delegation: Ratio of accounts trusted for unconstrained/constrained delagation, userAccountControl attribute: index=$ad_index$ host=$domain_host$ sourcetype=adobjects (ObjectClass = "user" OR ObjectClass = "inetOrgPerson" OR ObjectClass = "Computer") | eval eval_deleg_bit = floor(userAccountControl / pow(2, 19)) %2 | eval eval_cdeleg_bit = floor(userAccountControl / pow(2, 24)) %2 | search (eval_cdeleg_bit=1 OR eval_deleg_bit = 1 ) | eval eval_dc_bit = floor(userAccountControl / pow(2, 13)) %2 | eval eval_rodc_bit = floor(userAccountControl / pow(2, 26)) %2 | search eval_dc_bit = 0 AND eval_rodc_bit = 0 | eval DelegType =case(eval_cdeleg_bit == 1, "Account trusted for constrainded delegation", eval_deleg_bit == 1 , "Account trusted for unconstrainded delegation") | stats count as "Delegation type ratio" by DelegType $earliest$ $latest$ toto search?q=index=$ad_index$%20%20host=$domain_host$%20%20sourcetype=adobjects%20%20(ObjectClass%20=%20%22user%22%20OR%20ObjectClass%20=%20%22inetOrgPerson%22%20OR%20ObjectClass%20=%20%22Computer%22)%20%20%20%7C%20%20eval%20eval_deleg_bit%20=%20floor(userAccountControl%20/%20pow(2,%2019))%20%252%20%7C%20eval%20eval_cdeleg_bit%20=%20floor(userAccountControl%20/%20pow(2,%2024))%20%252%20%20%7C%20search%20(eval_cdeleg_bit=1%20OR%20eval_deleg_bit%20=%201%20)%20%7C%20%20eval%20eval_dc_bit%20=%20floor(userAccountControl%20/%20pow(2,%2013))%20%252%20%7C%20eval%20eval_rodc_bit%20=%20floor(userAccountControl%20/%20pow(2,%2026))%20%252%20%7C%20search%20eval_dc_bit%20=%200%20AND%20eval_rodc_bit%20=%200%20%7C%20eval%20DelegType%20=case(eval_cdeleg_bit%20==%201,%20%22Account%20trusted%20for%20constrainded%20delegation%22,%20eval_deleg_bit%20==%201%20%20,%20%22Account%20trusted%20for%20unconstrainded%20delegation%22)%20%7C%20search%20$click.name$%20=%20%22$click.value$%22&earliest=$earliest$&latest=$latest$

Ratio of accounts trusted for unconstrained/constrained delagation, userAccountControl attribute: No results

Accounts trusted for unconstrained delegation inventory, userAccountControl attribute: index=$ad_index$ host=$domain_host$ sourcetype=adobjects (ObjectClass = "user" OR ObjectClass = "inetOrgPerson" OR ObjectClass = "Computer") | eval eval_deleg_bit = floor(userAccountControl / pow(2, 19)) %2 | search eval_deleg_bit = 1 | eval eval_dc_bit = floor(userAccountControl / pow(2, 13)) %2 | eval eval_rodc_bit = floor(userAccountControl / pow(2, 26)) %2 | search eval_dc_bit = 0 AND eval_rodc_bit = 0 | eval Status = if((userAccountControl%4)>=2,"disabled","enabled") | eval Status = if((userAccountControl%4)>=2,"disabled","enabled") | eval lastlogon_timestamp = strftime(lastLogonTimestamp/10000000 - 11644473600, "%Y-%m-%dT%H:%M:%S") | table DN, ObjectClass, Status, lastlogon_timestamp, whenCreated 0 toto {"enabled":#A1D379,"disabled":#F8BE34} search?q=index=$ad_index$%20host=$domain_host$%20sourcetype=adobjects%20%20(ObjectClass%20=%20%22user%22%20OR%20ObjectClass%20=%20%22inetOrgPerson%22%20OR%20ObjectClass%20=%20%22Computer%22)%20%20%20%7C%20%20eval%20eval_deleg_bit%20=%20floor(userAccountControl%20/%20pow(2,%2019))%20%252%20%20%7C%20search%20%20eval_deleg_bit%20=%201%20%7C%20eval%20eval_dc_bit%20=%20floor(userAccountControl%20/%20pow(2,%2013))%20%252%20%7C%20%20eval%20eval_rodc_bit%20=%20floor(userAccountControl%20/%20pow(2,%2026))%20%252%20%7C%20search%20eval_dc_bit%20=%200%20AND%20eval_rodc_bit%20=%200%20%20%7C%20eval%20Status%20=%20if((userAccountControl%254)%3E=2,%22disabled%22,%22enabled%22)%20%7C%20eval%20Status%20=%20if((userAccountControl%254)%3E=2,%22disabled%22,%22enabled%22)%20%20%7C%20%20%20eval%20lastlogon_timestamp%20=%20strftime(lastLogonTimestamp/10000000%20-%2011644473600,%20%22%25Y-%25m-%25dT%25H:%25M:%25S%22)%20%7C%20search%20$click.name2$%20=%20%22$click.value2$%22&earliest=0&latest=

Accounts trusted for unconstrained delegation inventory, userAccountControl attribute: No results

Accounts trusted for constrained delegation inventory, userAccountControl attribute: index=$ad_index$ host=$domain_host$ sourcetype=adobjects (ObjectClass = "user" OR ObjectClass = "inetOrgPerson" OR ObjectClass = "Computer") | eval eval_cdeleg_bit = floor(userAccountControl / pow(2, 24)) %2 | search eval_cdeleg_bit=1 | eval eval_rodc_bit = floor(userAccountControl / pow(2, 26)) %2 | search eval_rodc_bit = 0 | rex "(?ms)msDS-AllowedToDelegateTo.{1,100}<LST>(?<AllowedToDelegateTotmp>.*?)</LST>" | eval AllowedToDelegateTo= replace(AllowedToDelegateTotmp, "(<(.|)S>|[\\n\r])" , "") | eval Status = if((userAccountControl%4)>=2,"disabled","enabled") | eval lastlogon_timestamp = strftime(lastLogonTimestamp/10000000 - 11644473600, "%Y-%m-%dT%H:%M:%S") | table DN, ObjectClass, AllowedToDelegateTo, Status, lastlogon_timestamp, whenCreated 0 toto {"enabled":#A1D379,"disabled":#F8BE34} search?q=index=$ad_index$%20host=$domain_host$%20%20sourcetype=adobjects%20%20(ObjectClass%20=%20%22user%22%20OR%20ObjectClass%20=%20%22inetOrgPerson%22%20OR%20ObjectClass%20=%20%22Computer%22)%20%7C%20eval%20eval_cdeleg_bit%20=%20floor(userAccountControl%20/%20pow(2,%2024))%20%252%20%7C%20search%20eval_cdeleg_bit=1%20%7C%20eval%20eval_rodc_bit%20=%20floor(userAccountControl%20/%20pow(2,%2026))%20%252%20%0A%7C%20search%20eval_rodc_bit%20=%200%20%0A%7C%20%20rex%20%22(%3Fms)msDS-AllowedToDelegateTo.%7B1,100%7D%3CLST%3E(%3F%3CAllowedToDelegateTotmp%3E.%2A%3F)%3C/LST%3E%22%20%7C%20eval%20AllowedToDelegateTo=%20replace(AllowedToDelegateTotmp,%20%22(%3C(.%7C)S%3E%7C%5B%5C%5Cn%5C%5Cr%5D)%22%20,%20%22%22)%20%7C%20eval%20Status%20=%20if((userAccountControl%254)%3E=2,%22disabled%22,%22enabled%22)%20%20%7C%20%20%20eval%20lastlogon_timestamp%20=%20strftime(lastLogonTimestamp/10000000%20-%2011644473600,%20%22%25Y-%25m-%25dT%25H:%25M:%25S%22)%20%7C%20search%20$click.name2$%20=%20%22$click.value2$%22&earliest=0&latest=

Accounts trusted for constrained delegation inventory, userAccountControl attribute: No results

Resource based constrained delegation inventory, msDS-AllowedToActOnBehalfOfOtherIdentity attribute: toto index=$ad_index$ host=$domain_host$ sourcetype="adobjects" (ObjectClass = "user" OR ObjectClass = "inetOrgPerson" OR ObjectClass = "Computer") | rex "(?ms)msDS-AllowedToActOnBehalfOfOtherIdentity.{1,1500}<MS>(?<AllowedToActOnBehalftmp>.*?)</MS>" | rex field=AllowedToActOnBehalftmp "AccessToString\">(?<AccountAllowedToActOnBehalf>.+)</S>" | search AccountAllowedToActOnBehalf = "*" | eval Status = if((userAccountControl%4)>=2,"disabled","enabled") | fillnull value="notset" adminCount | table DN, AccountAllowedToActOnBehalf, Status, adminCount 0 {"1":#D98491,"notset":#A1D379,"0":#A1D379} {"enabled":#A1D379,"disabled":#F8BE34} search?q=index=$ad_index$%20host=$domain_host$%20sourcetype=%22adobjects%22%20(ObjectClass%20=%20%22user%22%20OR%20ObjectClass%20=%20%22inetOrgPerson%22%20OR%20ObjectClass%20=%20%22Computer%22)%20%20%7C%20%20rex%20%22(%3Fms)msDS-AllowedToActOnBehalfOfOtherIdentity.%7B1,1500%7D%3CMS%3E(%3F%3CAllowedToActOnBehalftmp%3E.%2A%3F)%3C/MS%3E%22%20%0A%7C%20%20rex%20field=AllowedToActOnBehalftmp%20%22AccessToString%5C%22%3E(%3F%3CAccountAllowedToActOnBehalf%3E.%2B)%3C/S%3E%22%20%20%0A%7C%20%20search%20AccountAllowedToActOnBehalf%20=%20%22*%22%20%0A%7C%20%20eval%20Status%20=%20if((userAccountControl%254)%3E=2,%22disabled%22,%22enabled%22)%20%7C%20fillnull%20value=%22notset%22%20adminCount%20%7C%20search%20$click.name2$%20=%20%22$click.value2$%22&earliest=0&latest=

Resource based constrained delegation inventory, msDS-AllowedToActOnBehalfOfOtherIdentity attribute: No results

================================================ FILE: SA-ADTimeline/default/data/ui/views/suspicious_activity.xml ================================================
index=$ad_index$ host=$domain_host$ sourcetype=adtimeline | where usnLocalChange = usnOriginatingChange | stats earliest(_time) as firstevent | fields firstevent 0 $result.firstevent$
| tstats latest(_time) where index=* by index true index index | tstats latest(_time) where index=$ad_index$ (sourcetype=adobjects OR sourcetype=gcobjects OR sourcetype=adtimeline) by host true host host

ACL modifications

MITRE | ATT&CK T1098

ACL modifications performed one year back, stats by ObjectClass per week: index=$ad_index$ host=$domain_host$ sourcetype=adtimeline pszAttributeName="nTSecurityDescriptor" dwVersion >= 2 | eval ObjectClass=if(ObjectClass=="System.DirectoryServices.ResultPropertyValueCollection","GCobject_ObjectClassNA",ObjectClass) | timechart span=1w count by ObjectClass limit=0 -1y now if(isnull($row._time$),1,$row._time$) if(isnull($row._time$),now(),$row._time$ + $row._span$) search?q=index=$ad_index$%20host=$domain_host$%20sourcetype=adtimeline%20pszAttributeName=%22nTSecurityDescriptor%22%20%20dwVersion%20%3E=%202%20%20%7C%20eval%20ObjectClass=if(ObjectClass==%22System.DirectoryServices.ResultPropertyValueCollection%22,%22GCobject_ObjectClassNA%22,ObjectClass)%0A%7C%20%20search%20%20ObjectClass%20=%20%22$click.name2$%22&earliest=$drilldown.earliest$&latest=$drilldown.latest$ ACL modifications on AdminSDHolder and DomainDNS object: index=$ad_index$ host=$domain_host$ sourcetype=adtimeline pszAttributeName="nTSecurityDescriptor" (ObjectClass = "DomainDNS" OR (Name= "AdminSDHolder" AND ObjectClass="container")) | makemv pszLastOriginatingDsaDN delim=",CN=" | eval OriginatingDC = mvindex(pszLastOriginatingDsaDN, 1, 1) | table _time, Name, pszAttributeName, dwVersion, OriginatingDC 0 search?q=index=$ad_index$%20host=$domain_host$%20((sourcetype=adtimeline%20AND%20pszAttributeName=%22nTSecurityDescriptor%22)%20OR%20sourcetype=adobjects)%20%20AND%20(ObjectClass%20=%20%22DomainDNS%22%20OR%20(Name=%20%22AdminSDHolder%22%20AND%20ObjectClass=%22container%22))%20%7C%20%20makemv%20pszLastOriginatingDsaDN%20delim=%22,CN=%22%20%7C%20eval%20OriginatingDC%20=%20mvindex(pszLastOriginatingDsaDN,%201,%201)&earliest=0&latest=
User or computers accounts having an ACE on DomainDNS object: toto index=$ad_index$ host=$domain_host$ sourcetype=adtimeline (ObjectCategory = "CN=Person,CN=Schema*" OR ObjectCategory = "CN=Computer,CN=Schema*") [search index=$ad_index$ host=$domain_host$ sourcetype=adobjects ObjectClass = "DomainDNS" | rex field=SDDL "(?<Sid>S-1-5-21-\d{8,10}-\d{8,10}-\d{8,10}-\d{4,10})" max_match=0 | stats count by Sid | return 1000 $Sid] | stats count by DN, SID | table DN, SID 0 search?q=index=$ad_index$%20host=$domain_host$%20%20((sourcetype=adtimeline%20OR%20sourcetype=adobjects%20OR%20sourcetype=gcobjects)%20AND%20(ObjectCategory%20=%20%22CN=Person,CN=Schema*%22%20%20OR%20ObjectCategory%20=%20%22CN=Computer,CN=Schema*%22))%20OR%20(sourcetype=adobjects%20%20AND%20ObjectClass%20=%20%22DomainDNS%22)%20%20%5Bsearch%20index=$ad_index$%20host=$domain_host$%20%20sourcetype=adobjects%20%20ObjectClass%20=%20%22DomainDNS%22%20%7C%20rex%20field=SDDL%20%22(%3F%3CSid%3ES-1-5-21-%5Cd%7B8,10%7D-%5Cd%7B8,10%7D-%5Cd%7B8,10%7D-%5Cd%7B4,10%7D)%22%20max_match=0%20%20%7C%20%20stats%20count%20by%20Sid%20%7C%20return%201000%20$Sid%5D%20%7C%20search%20$click.name2$%20=%20%22$click.value2$%22%20OR%20ObjectClass%20=%20%22DomainDNS%22&earliest=0&latest=

User or computers accounts having an ACE on DomainDNS object: No results

User or computers accounts having an ACE on AdminSDHolder object: toto index=$ad_index$ host=$domain_host$ sourcetype=adtimeline (ObjectCategory = "CN=Person,CN=Schema*" OR ObjectCategory = "CN=Computer,CN=Schema*") [search index=$ad_index$ host=$domain_host$ sourcetype=adobjects (ObjectClass = "container" AND Name= "AdminSDHolder") | rex field=SDDL "(?<Sid>S-1-5-21-\d{8,10}-\d{8,10}-\d{8,10}-\d{4,10})" max_match=0 | stats count by Sid | return 1000 $Sid] | stats count by DN,SID | table DN,SID 0 search?q=index=$ad_index$%20host=$domain_host$%20%20((sourcetype=adtimeline%20OR%20sourcetype=adobjects%20OR%20sourcetype=gcobjects)%20AND%20%20(ObjectCategory%20=%20%22CN=Person,CN=Schema*%22%20%20OR%20ObjectCategory%20=%20%22CN=Computer,CN=Schema*%22))%20OR%20(ObjectClass%20=%20%22container%22%20AND%20Name=%20%22AdminSDHolder%22)%20%5Bsearch%20index=$ad_index$%20host=$domain_host$%20%20sourcetype=adobjects%20%20(ObjectClass%20=%20%22container%22%20AND%20Name=%20%22AdminSDHolder%22)%20%7C%20%20rex%20field=SDDL%20%22(%3F%3CSid%3ES-1-5-21-%5Cd%7B8,10%7D-%5Cd%7B8,10%7D-%5Cd%7B8,10%7D-%5Cd%7B4,10%7D)%22%20max_match=0%20%20%7C%20%20stats%20count%20by%20Sid%20%7C%20return%201000%20$Sid%5D%20%7C%20search%20$click.name2$%20=%20%22$click.value2$%22%20OR%20ObjectClass%20=%20%22container%22&earliest=0&latest=

User or computers accounts having an ACE on AdminSDHolder object: No results

ACL modifications by ObjectClass: index=$ad_index$ host=$domain_host$ sourcetype=adtimeline pszAttributeName="nTSecurityDescriptor" dwVersion >= 2 | eval ObjectClass=if(ObjectClass=="System.DirectoryServices.ResultPropertyValueCollection","GCobject_ObjectClassNA",ObjectClass) | stats count by ObjectClass 0 search?q=index=$ad_index$%20host=$domain_host$%20sourcetype=adtimeline%20pszAttributeName=%22nTSecurityDescriptor%22%20%20dwVersion%20%3E=%202%20%7C%20eval%20ObjectClass=if(ObjectClass==%22System.DirectoryServices.ResultPropertyValueCollection%22,%22GCobject_ObjectClassNA%22,ObjectClass)%20%7C%20search%20$click.name$%20=%20%22$click.value$%22&earliest=0&latest= Least frequent object owners: index=$ad_index$ host=$domain_host$ sourcetype=adobjects | stats values(DN) count by Owner | where count < 3 | sort count | table Owner, values(DN), count | rename values(DN) AS "Objects owned" 0 search?q=index=$ad_index$%20host=$domain_host$%20%20sourcetype=adobjects%20%20%7C%20stats%20values(DN)%20count%20by%20Owner%20%7C%20where%20count%20%3C%203%20%7C%20sort%20count%20%7C%20table%20Owner,%20values(DN),%20count%20%7C%20rename%20values(DN)%20AS%20%22Objects%20owned%22&earliest=0&latest=
User and computer accounts

MITRE | ATT&CK T1110, T1531

Account lockouts index=$ad_index$ host=$domain_host$ sourcetype=adtimeline pszAttributeName="lockoutTime" | timechart span=1week count by pszAttributeName limit=0 0 toto if(isnull($row._time$),1,$row._time$) if(isnull($row._time$),now(),$row._time$ + $row._span$) search?q=index=$ad_index$%20host=$domain_host$%20sourcetype=adtimeline%20pszAttributeName=%22lockoutTime%22&earliest=$drilldown.earliest$&latest=$drilldown.latest$ Top 5 account lockouts toto index=$ad_index$ host=$domain_host$ sourcetype=adtimeline pszAttributeName="lockoutTime" | sort -dwVersion | head 5 | table _time, DN, dwVersion 0 search?q=index=$ad_index$%20%20host=$domain_host$%20%20sourcetype=adtimeline%20pszAttributeName=%22lockoutTime%22%20%7C%20sort%20-dwVersion%20%7C%20head%205%20%7C%20search%20$click.name2$%20=%20%22$click.value2$%22&earliest=0&latest=

Top 5 account lockouts: No results

Account lockouts: No results

MITRE | ATT&CK T1098, T1531

Accounts added and removed from groups, frequency: toto index=$ad_index$ host=$domain_host$ sourcetype=adtimeline ObjectClass="group" pszAttributeName="Member" dwVersion != 0 | eval Test= if(dwVersion%2==0,"Even","odd") | search Test="Even" | stats count by dwVersion 0 search?q=index=$ad_index$%20host=$domain_host$%20sourcetype=adtimeline%20ObjectClass=%22group%22%20pszAttributeName=%22Member%22%20dwVersion%20!=%200%20%20%7C%20eval%20Test=%20if(dwVersion%252==0,%22Even%22,%22odd%22)%20%7C%20search%20Test=%22Even%22%20%7C%20search%20$click.name$%20=%20%22$click.value$%22&earliest=0&latest=

Accounts added and removed from groups, frequency: No results

Accounts added and removed from groups, membership time in days: toto index=$ad_index$ host=$domain_host$ sourcetype=adtimeline ObjectClass="group" pszAttributeName="Member" dwVersion != 0 | eval Test= if(dwVersion%2==0,"Even","odd") | search Test="Even" | eval ftimeCreatedT = strptime(ftimeCreated, "%Y-%m-%dT%H:%M:%SZ") | eval ftimeDeletedT = if(ftimeDeleted=="1601-01-01T00:00:00Z", strptime(ftimeLastOriginatingChange,"%Y-%m-%dT%H:%M:%SZ"), strptime(ftimeDeleted, "%Y-%m-%dT%H:%M:%SZ")) | fillnull value=0 ftimeDeletedT | eval TimeDiff = floor((ftimeDeletedT - ftimeCreatedT) / 86400) | stats count by TimeDiff 0 search?q=index=$ad_index$%20host=$domain_host$%20sourcetype=adtimeline%20ObjectClass=%22group%22%20pszAttributeName=%22Member%22%20dwVersion%20!=%200%20%20%7C%20eval%20Test=%20if(dwVersion%252==0,%22Even%22,%22odd%22)%20%7C%20search%20Test=%22Even%22%20%7C%20eval%20ftimeCreatedT%20=%20strptime(ftimeCreated,%20%22%25Y-%25m-%25dT%25H:%25M:%25SZ%22)%20%7C%20eval%20ftimeDeletedT%20%3D%20if(ftimeDeleted%3D%3D%221601-01-01T00%3A00%3A00Z%22%2C%20strptime(ftimeLastOriginatingChange%2C%22%25Y-%25m-%25dT%25H%3A%25M%3A%25SZ%22)%2C%20strptime(ftimeDeleted%2C%20%22%25Y-%25m-%25dT%25H%3A%25M%3A%25SZ%22))%20%7C%20fillnull%20value=0%20ftimeDeletedT%20%7C%20eval%20TimeDiff%20=%20floor((ftimeDeletedT%20-%20ftimeCreatedT)%20/%2086400)%20%7C%20search%20$click.name$%20=%20%22$click.value$%22&earliest=0&latest=

Accounts added and removed from groups, membership time in days: No results

Accounts added and removed from groups, member account OU: toto index=$ad_index$ host=$domain_host$ sourcetype=adtimeline ObjectClass="group" pszAttributeName="Member" dwVersion != 0 | eval Test= if(dwVersion%2==0,"Even","odd") | search Test="Even" | makemv Member delim="," | eval Member_OU = mvjoin(mvindex(Member, 1, mvcount(Member)),",") | stats count by Member_OU 0 search?q=index=$ad_index$%20host=$domain_host$%20sourcetype=adtimeline%20ObjectClass=%22group%22%20pszAttributeName=%22Member%22%20dwVersion%20!=%200%20%7C%20eval%20Test=%20if(dwVersion%252==0,%22Even%22,%22odd%22)%20%7C%20search%20Test=%22Even%22%20%7C%20makemv%20Member%20delim=%22,%22%20%7C%20eval%20Member_OU%20=%20mvjoin(mvindex(Member,%201,%20mvcount(Member)),%22,%22)%20%7C%20search%20$click.name$%20=%20%22$click.value$%22&earliest=0&latest=

Accounts added and removed from groups, member account OU: No results

MITRE | ATT&CK T1178

SIDHistory and primaryGroupID editions index=$ad_index$ host=$domain_host$ sourcetype=adtimeline pszAttributeName="SIDHistory" OR (pszAttributeName="primaryGroupID" AND dwVersion > 1 AND NOT DN = "*,OU=Domain Controllers,*") AND NOT (Name = "*DEL\:*" AND ObjectClass = "Computer") | timechart span=1week count by pszAttributeName limit=0 0 toto if(isnull($row._time$),1,$row._time$) if(isnull($row._time$),now(),$row._time$ + $row._span$) search?q=index=$ad_index$%20%20host=$domain_host$%20sourcetype=adtimeline%20pszAttributeName=%22SIDHistory%22%20%20OR%20(pszAttributeName=%22primaryGroupID%22%20AND%20dwVersion%20%3E%201%20AND%20NOT%20DN%20=%20%22*,OU=Domain%20Controllers,*%22)%20AND%20NOT%20(Name%20=%20%22*DEL%5C:*%22%20AND%20ObjectClass%20=%20%22Computer%22)%20%7C%20%20search%20%20pszAttributeName%20=%20%22$click.name2$%22&earliest=$drilldown.earliest$&latest=$drilldown.latest$

SIDHistory and primaryGroupID editions: No results

Suspicious SIDHistory values index=$ad_index$ host=$domain_host$ (sourcetype=adobjects AND (ObjectClass = "user" OR ObjectClass = "inetOrgPerson" OR ObjectClass = "Computer" OR ObjectClass = "Group")) OR sourcetype=gcobjects | rex "(?ms)sIDHistory.{1,100}<LST>(?<SIDHistories>.*?)</LST>" | rex field=SIDHistories "(?<Sid2>(S-1-5-21-\d{8,10}-\d{8,10}-\d{8,10}-\d{3,10}|S-1-5-32-\d{3}))" max_match=0 | rex field=_raw "sidhistory\">(?<SIDHistories>.+?)</S>" | rex field=SIDHistories "(?<Sid1>(S-1-5-21-\d{8,10}-\d{8,10}-\d{8,10}-\d{3,10}|S-1-5-32-\d{3}))" max_match=0 | eval sidHs = mvappend(Sid1,Sid2) | dedup sidHs | mvexpand sidHs | dedup sidHs | rex field=SID "(?<DomainSid>S-1-5-21-\d{8,10}-\d{8,10}-\d{8,10})" | eval SuspiciousSIDHistory = if(like(sidHs,DomainSid."%") OR like(sidHs,"%-500") OR like(sidHs,"%-518") OR like(sidHs,"%-498") OR like(sidHs,"%-519") OR like(sidHs,"%-512") OR like(sidHs,"%-516") OR sidHs="S-1-5-32-550" OR sidHs="S-1-5-32-549" OR sidHs="S-1-5-32-551" OR sidHs="S-1-5-32-544" OR sidHs="S-1-5-32-548" ,sidHs,null) | search SuspiciousSIDHistory = "*" | join SID [search index=$ad_index$ host=$domain_host$ sourcetype=adtimeline pszAttributeName=sIDHistory | rename _time as LastSIDHistoryEditiontimeepoch | fields LastSIDHistoryEditiontimeepoch, SID, dwVersion] | eval LastSIDHistoryEditiontime = strftime(LastSIDHistoryEditiontimeepoch,"%Y-%m-%d %H:%M:%S") | table LastSIDHistoryEditiontime, DN, SuspiciousSIDHistory, SID, dwVersion | sort -LastSIDHistoryEditiontime 0 toto search?q=index=$ad_index$%20%20host=$domain_host$%20%20(sourcetype=adobjects%20AND%20(ObjectClass%20=%20%22user%22%20OR%20ObjectClass%20=%20%22inetOrgPerson%22%20OR%20ObjectClass%20=%20%22Computer%22%20OR%20ObjectClass%20=%20%22Group%22))%20OR%20sourcetype=gcobjects%20%0A%7C%20%20rex%20%20%22(%3Fms)sIDHistory.%7B1,100%7D%3CLST%3E(%3F%3CSIDHistories%3E.%2A%3F)%3C/LST%3E%22%20%7C%20rex%20field=SIDHistories%20%22(%3F%3CSid2%3E(S-1-5-21-%5Cd%7B8,10%7D-%5Cd%7B8,10%7D-%5Cd%7B8,10%7D-%5Cd%7B3,10%7D%7CS-1-5-32-%5Cd%7B3%7D))%22%20max_match=0%20%0A%7C%20rex%20field=_raw%20%22sidhistory%5C%22%3E(%3F%3CSIDHistories%3E.%2B%3F)%3C/S%3E%22%0A%7C%20rex%20field=SIDHistories%20%22(%3F%3CSid1%3E(S-1-5-21-%5Cd%7B8,10%7D-%5Cd%7B8,10%7D-%5Cd%7B8,10%7D-%5Cd%7B3,10%7D%7CS-1-5-32-%5Cd%7B3%7D))%22%20max_match=0%20%7C%20eval%20sidHs%20=%20mvappend(Sid1,Sid2)%0A%7C%20%20dedup%20sidHs%20%7C%20%20mvexpand%20sidHs%20%0A%7C%20%20dedup%20sidHs%0A%7C%20%20rex%20field=SID%20%22(%3F%3CDomainSid%3ES-1-5-21-%5Cd%7B8,10%7D-%5Cd%7B8,10%7D-%5Cd%7B8,10%7D)%22%20%0A%7C%20%20eval%20SuspiciousSIDHistory%20=%20if(like(sidHs,DomainSid.%22%25%22)%20OR%20like(sidHs,%22%25-500%22)%20%20OR%20like(sidHs,%22%25-518%22)%20OR%20like(sidHs,%22%25-498%22)%20OR%20like(sidHs,%22%25-519%22)%20OR%20like(sidHs,%22%25-512%22)%20OR%20like(sidHs,%22%25-516%22)%20OR%20sidHs=%22S-1-5-32-550%22%20OR%20sidHs=%22S-1-5-32-549%22%20OR%20sidHs=%22S-1-5-32-551%22%20OR%20sidHs=%22S-1-5-32-544%22%20%20OR%20sidHs=%22S-1-5-32-548%22%20,sidHs,null)%0A%7C%20search%20SuspiciousSIDHistory%20=%20%22*%22%20%7C%20%20join%20SID%20%0A%20%20%20%20%5Bsearch%20index=$ad_index$%20%20host=$domain_host$%20%20sourcetype=adtimeline%20pszAttributeName=sIDHistory%20%0A%20%20%20%20%7C%20%0A%20%20%20%20rename%20_time%20as%20LastSIDHistoryEditiontimeepoch%20%7C%20%20fields%20LastSIDHistoryEditiontimeepoch,%20SID,%20dwVersion%5D%20%0A%7C%20%20eval%20LastSIDHistoryEditiontime%20=%20strftime(LastSIDHistoryEditiontimeepoch,%22%25Y-%25m-%25d%20%25H:%25M:%25S%22)%20%0A%7C%20search%20$click.name2$%20=%20%22$click.value2$%22&earliest=0&latest=

Suspicious SIDHistory values: No results

MITRE | ATT&CK T1098

Possible password backdoor: Compare dBCSPwd LmPwdHistory ntPwdHistory unicodePwd and supplementalCredentials attributes modification date index=$ad_index$ host=$domain_host$ sourcetype=adtimeline (ObjectClass="user" OR ObjectClass="inetOrgPerson" OR ObjectClass="Computer") (pszAttributeName="dBCSPwd" OR pszAttributeName="lmPwdHistory" OR pszAttributeName="ntPwdHistory" OR pszAttributeName="unicodePwd" OR pszAttributeName="supplementalCredentials") AND NOT (Name = "*DEL\:*") | makemv pszLastOriginatingDsaDN delim=",CN=" | eval OriginatingDC = mvindex(pszLastOriginatingDsaDN, 1, 1) | bucket _time span=5m | stats list(pszAttributeName) count by _time, DN, OriginatingDC | search count < 4 | rename list(pszAttributeName) AS "Attributes modified" 0 toto search?q=index=$ad_index$%20%20host=$domain_host$%20sourcetype=adtimeline%20(ObjectClass=%22user%22%20OR%20ObjectClass=%22inetOrgPerson%22%20OR%20ObjectClass=%22Computer%22)%20(pszAttributeName=%22dBCSPwd%22%20%20OR%20pszAttributeName=%22lmPwdHistory%22%20OR%20pszAttributeName=%22ntPwdHistory%22%20OR%20pszAttributeName=%22unicodePwd%22%20OR%20pszAttributeName=%22supplementalCredentials%22)%20AND%20NOT%20(Name%20=%20%22*DEL%5C:*%22)%20%20%7C%20makemv%20pszLastOriginatingDsaDN%20delim=%22,CN=%22%20%7C%20eval%20OriginatingDC%20=%20mvindex(pszLastOriginatingDsaDN,%201,%201)%20%7C%20%20bucket%20_time%20span=5m%20%7C%20stats%20list(pszAttributeName)%20count%20by%20_time,%20DN,%20OriginatingDC%20%0A%7C%20rename%20list(pszAttributeName)%20AS%20%22Attributes%20modified%22%20%0A%7C%20search%20$click.name2$%20=%20%22$click.value2$%22&earliest=0&latest=

Possible password backdoor: No results

Resource based constrained delegation on privileged account or Domain Controller: msDS-AllowedToActOnBehalfOfOtherIdentity attribute toto index=$ad_index$ host=$domain_host$ sourcetype=adtimeline pszAttributeName = "msDS-AllowedToActOnBehalfOfOtherIdentity" [search index=$ad_index$ host=$domain_host$ sourcetype=adobjects (ObjectClass = "user" OR ObjectClass = "inetOrgPerson" OR ObjectClass = "Computer") | eval eval_dc_bit = floor(userAccountControl / pow(2, 13)) %2 | eval eval_rodc_bit = floor(userAccountControl / pow(2, 26)) %2 | search ((eval_dc_bit = 1 OR eval_rodc_bit = 1) AND DN = "*,OU=Domain Controllers,*") OR adminCount=1 | fields DN] | makemv pszLastOriginatingDsaDN delim=",CN=" | eval OriginatingDC = mvindex(pszLastOriginatingDsaDN, 1, 1) | sort -_time | table _time, DN, pszAttributeName, OriginatingDC 0 search?q=index=$ad_index$%20host=$domain_host$%20sourcetype=adtimeline%20%20(pszAttributeName%20=%20%22msDS-AllowedToActOnBehalfOfOtherIdentity%22%20OR%20pszAttributeName%20=%20%22pwdLastSet%22)%20%5Bsearch%20index=$ad_index$%20host=$domain_host$%20sourcetype=adobjects%20%20(ObjectClass%20=%20%22user%22%20OR%20ObjectClass%20=%20%22inetOrgPerson%22%20OR%20ObjectClass%20=%20%22Computer%22)%20%20%7C%20%20eval%20eval_dc_bit%20=%20floor(userAccountControl%20/%20pow(2,%2013))%20%252%20%7C%20%20eval%20eval_rodc_bit%20=%20floor(userAccountControl%20/%20pow(2,%2026))%20%252%20%7C%20search%20((eval_dc_bit%20=%201%20OR%20eval_rodc_bit%20=%201)%20%20AND%20DN%20=%20%22*,OU=Domain%20Controllers,*%22)%20OR%20%20adminCount=1%20%7C%20fields%20DN%5D%20%7C%20makemv%20pszLastOriginatingDsaDN%20delim=%22,CN=%22%20%7C%20eval%20OriginatingDC%20=%20mvindex(pszLastOriginatingDsaDN,%201,%201)%20%7C%20%20search%20$click.name2$%20=%20%22$click.value2$%22&earliest=0&latest=

Resource based constrained delegation on privileged account or Domain Controller: No results

MITRE | ATT&CK T1112

Domain Controller password change frequency: index=$ad_index$ host=$domain_host$ sourcetype=adobjects ObjectClass= "Computer" DN = "*,OU=Domain Controllers,*" | eval eval_dc_bit = floor(userAccountControl / pow(2, 13)) %2 | eval eval_rodc_bit = floor(userAccountControl / pow(2, 26)) %2 | search eval_dc_bit = 1 OR eval_rodc_bit = 1 | rex field=_raw "pwdLastSet\">(?<pwdLastSet>.+?)</I64>" | eval TimeDiff = round((lastLogonTimestamp - pwdLastSet) / (10000000 * 60 * 60 * 24)) | eval DiffPwdLastSet= if(TimeDiff < 32,"OK less than 31 days","NOK more than 31 days") | stats count by DiffPwdLastSet 0 toto search?q=index=$ad_index$%20host=$domain_host$%20sourcetype=adobjects%20%20ObjectClass=%20%22Computer%22%20DN%20=%20%22*,OU=Domain%20Controllers,*%22%20%7C%20%20eval%20eval_dc_bit%20=%20floor(userAccountControl%20/%20pow(2,%2013))%20%252%20%7C%20%20eval%20eval_rodc_bit%20=%20floor(userAccountControl%20/%20pow(2,%2026))%20%252%20%7C%20search%20eval_dc_bit%20=%201%20OR%20eval_rodc_bit%20=%201%20%7C%20rex%20field=_raw%20%22pwdLastSet%5C%22%3E(%3F%3CpwdLastSet%3E.%2B%3F)%3C/I64%3E%22%0A%7C%20%20eval%20TimeDiff%20=%20round((lastLogonTimestamp%20-%20pwdLastSet)%20/%20(10000000%20*%2060%20*%2060%20*%2024))%20%0A%7C%20%20eval%20DiffPwdLastSet=%20if(TimeDiff%20%3C%2032,%22OK%20less%20than%2031%20days%22,%22NOK%20more%20than%2031%20days%22)%20%0A%7C%20%20search%20$click.name$%20=%20%22$click.value$%22&earliest=0&latest=

Domain Controller password change frequency: No results

GPOs

MITRE | ATT&CK T1484

Modifications on GPOs configuring audit settings: index=$ad_index$ host=$domain_host$ sourcetype=adtimeline ((pszAttributeName = "gPCMachineExtensionNames" OR pszAttributeName = "nTSecurityDescriptor" OR pszAttributeName = "versionNumber") AND dwVersion >= 2) OR pszAttributeName = "whenCreated" [search index=$ad_index$ host=$domain_host$ sourcetype="adobjects" ObjectClass=groupPolicyContainer ("*F3CCC681-B74C-4060-9F26-CD84525DCA2A*" OR "*0F3F3735-573D-9804-99E4-AB2A69BA5FD4*") | fields DN] | makemv pszLastOriginatingDsaDN delim=",CN=" | eval OriginatingDC = mvindex(pszLastOriginatingDsaDN, 1, 1) | join DN [search index=$ad_index$ host=$domain_host$ ObjectClass=groupPolicyContainer ("*F3CCC681-B74C-4060-9F26-CD84525DCA2A*" OR "*0F3F3735-573D-9804-99E4-AB2A69BA5FD4*") | fields DN, DisplayName] | join Name [search index=$ad_index$ host=$domain_host$ sourcetype="adobjects" (ObjectClass = "domainDNS" OR ObjectClass = "site" OR ObjectClass = "organizationalUnit") | rex field=_raw "gPLink\">(?<gPLink>.+?)</S>" | search gPLink = "*" | rex field=gPLink "(CN|cn)\=(?<Name>\{.+?\})," max_match=0 | mvexpand Name | stats values(DN) as Links by Name | fields Name, Links ] | table _time, DisplayName, pszAttributeName, dwVersion, Links, Name, OriginatingDC | sort -_time 0 toto search?q=index=$ad_index$%20host=$domain_host$%20sourcetype=adtimeline%20%20%20%5Bsearch%20index=$ad_index$%20host=$domain_host$%20sourcetype=%22adobjects%22%20ObjectClass=groupPolicyContainer%20(%22*F3CCC681-B74C-4060-9F26-CD84525DCA2A*%22%20OR%20%22*0F3F3735-573D-9804-99E4-AB2A69BA5FD4*%22)%20%7C%20fields%20DN%5D%20%0A%7C%20%20makemv%20pszLastOriginatingDsaDN%20delim=%22,CN=%22%20%7C%20eval%20OriginatingDC%20=%20mvindex(pszLastOriginatingDsaDN,%201,%201)%20%0A%7C%20join%20DN%20%5Bsearch%20%20index=$ad_index$%20host=$domain_host$%20ObjectClass=groupPolicyContainer%20(%22*F3CCC681-B74C-4060-9F26-CD84525DCA2A*%22%20OR%20%22*0F3F3735-573D-9804-99E4-AB2A69BA5FD4*%22)%20%7C%20fields%20DN,%20DisplayName%5D%20%20%0A%7C%20%20join%20Name%20%0A%20%20%20%20%5Bsearch%20index=$ad_index$%20host=$domain_host$%20sourcetype=%22adobjects%22%20(ObjectClass%20=%20%22domainDNS%22%20OR%20ObjectClass%20=%20%22site%22%20OR%20ObjectClass%20=%20%22organizationalUnit%22)%20%20%7C%20rex%20field=_raw%20%22gPLink%5C%22%3E(%3F%3CgPLink%3E.%2B%3F)%3C/S%3E%22%20%0A%20%7C%20%20search%20%20gPLink%20=%20%22*%22%20%0A%7C%20%20rex%20field=gPLink%20%22(CN%7Ccn)%5C=(%3F%3CName%3E%5C%7B.%2B%3F%5C%7D),%22%20max_match=0%20%0A%7C%20mvexpand%20Name%0A%7C%20%20stats%20values(DN)%20as%20Links%20by%20Name%20%0A%7C%20%20fields%20Name,%20Links%20%5D%0A%7C%20%20search%20$click.name2$%20=%20%22$click.value2$%22&earliest=0&latest=

Modifications on GPOs configuring audit settings: No results

Modifications breaking GPO processing: toto index=$ad_index$ host=$domain_host$ sourcetype="adtimeline" ObjectClass=groupPolicyContainer ((pszAttributeName="versionNumber" OR pszAttributeName="gPCFunctionalityVersion") AND dwVersion > 1) OR (pszAttributeName="gPCFileSysPath" AND dwVersion > 2) | join DN [search index=$ad_index$ host=$domain_host$ sourcetype="adobjects" ObjectClass=groupPolicyContainer | rex field=_raw "versionNumber\">(?<versionNumber>.+?)</I32>" | fields DN, DisplayName, versionNumber] | search pszAttributeName="gPCFileSysPath" OR pszAttributeName="gPCFunctionalityVersion" OR (pszAttributeName="versionNumber" AND versionNumber = 0) | table _time, DisplayName, pszAttributeName, dwVersion 0

Modifications breaking GPO processing: No results

DCShadow detection

MITRE | ATT&CK T1207

Possible DCShadow operations: index=$ad_index$ host=$domain_host$ sourcetype=adtimeline (ObjectClass="Server" OR ObjectClass="nTDSDSA") pszAttributeName="Isdeleted" | eval whencreate=strptime(WhenCreated,"%Y-%m-%d %H:%M:%S%Z") | eval timediff = _time - whencreate | search timediff < 10 | timechart span=1week count by pszAttributeName limit=0 0 toto if(isnull($row._time$),1,$row._time$) if(isnull($row._time$),now(),$row._time$ + 604800) search?q=index=$ad_index$%20host=$domain_host$%20sourcetype=adtimeline%20(ObjectClass=%22Server%22%20OR%20ObjectClass=%22nTDSDSA%22)%20pszAttributeName=%22Isdeleted%22%20%7C%20eval%20whencreate=strptime(WhenCreated,%22%25Y-%25m-%25d%20%25H:%25M:%25S%25Z%22)%20%20%7C%20eval%20timediff%20=%20_time%20-%20whencreate%20%7C%20search%20timediff%20%3C%2010&earliest=$drilldown.earliest$&latest=$drilldown.latest$

Possible DCShadow operations: No results

Possible metadata timestomping, usnOriginatingChange detection: index=$ad_index$ host=$domain_host$ sourcetype=adtimeline | sort 0 uuidLastOriginatingDsaInvocationID, usnOriginatingChange | autoregress usnOriginatingChange as Previous_usnOriginatingChange p=1 | autoregress ftimeLastOriginatingChange as Previous_ftimeLastOriginatingChange p=1 | autoregress uuidLastOriginatingDsaInvocationID as Previous_uuidLastOriginatingDsaInvocationID p=1 | delta _time AS timeDelta | search (timeDelta < -60 NOT (ObjectClass="container" AND Name="Deleted Objects")) | where uuidLastOriginatingDsaInvocationID = Previous_uuidLastOriginatingDsaInvocationID | stats count, list(DN) as DNs, list(pszAttributeName) as pszAttributeNames, list(usnOriginatingChange) as usnOriginatingChanges list(Previous_usnOriginatingChange) as prev_usnOriginatingChanges list(ftimeLastOriginatingChange) as ModificationTimes list(Previous_ftimeLastOriginatingChange) as prev_ModificationTimes by uuidLastOriginatingDsaInvocationID, pszLastOriginatingDsaDN | where count > 1 | makemv pszLastOriginatingDsaDN delim=",CN=" | eval OriginatingDC = mvindex(pszLastOriginatingDsaDN, 1, 1) | table usnOriginatingChanges, prev_usnOriginatingChanges, DNs, pszAttributeNames, ModificationTimes,prev_ModificationTimes, OriginatingDC, uuidLastOriginatingDsaInvocationID 0 toto search?q=index=$ad_index$%20host=$domain_host$%20sourcetype=adtimeline%20%20%7C%20sort%200%20%20uuidLastOriginatingDsaInvocationID,%20usnOriginatingChange%20%20%7C%20autoregress%20usnOriginatingChange%20as%20Previous_usnOriginatingChange%20p=1%20%7C%20autoregress%20ftimeLastOriginatingChange%20as%20Previous_ftimeLastOriginatingChange%20p=1%20%7C%20autoregress%20uuidLastOriginatingDsaInvocationID%20as%20Previous_uuidLastOriginatingDsaInvocationID%20p=1%20%7C%20delta%20_time%20AS%20timeDelta%20%7C%20search%20(timeDelta%20%3C%20-60%20NOT%20(ObjectClass=%22container%22%20AND%20Name=%22Deleted%20Objects%22))%20%20%7C%20where%20uuidLastOriginatingDsaInvocationID%20=%20Previous_uuidLastOriginatingDsaInvocationID&earliest=0&latest=

Possible metadata timestomping, usnOriginatingChange detection: No results

Possible metadata timestomping, usnLocalChange detection: toto index=$ad_index$ host=$domain_host$ sourcetype=adtimeline earliest="$Dcinstall$" | sort 0 usnLocalChange | delta _time AS timeDelta | autoregress usnLocalChange as Previous_usnLocalChange p=1 | autoregress ftimeLastOriginatingChange as Previous_ftimeLastOriginatingChange p=1 | search (timeDelta < -2592000 NOT (ObjectClass="container" AND Name="Deleted Objects")) | makemv pszLastOriginatingDsaDN delim=",CN=" | eval OriginatingDC = mvindex(pszLastOriginatingDsaDN, 1, 1) | table usnLocalChange , DN, pszAttributeName, ftimeLastOriginatingChange, OriginatingDC, uuidLastOriginatingDsaInvocationID, Previous_usnLocalChange, Previous_ftimeLastOriginatingChange 0 now search?q=index=$ad_index$%20host=$domain_host$%20sourcetype=adtimeline%20earliest=%22$Dcinstall$%22%20%7C%20sort%200%20usnLocalChange%20%20%7C%20delta%20_time%20AS%20timeDelta%20%7C%20%20%20autoregress%20usnLocalChange%20as%20Previous_usnLocalChange%20p=1%20%7C%20autoregress%20ftimeLastOriginatingChange%20as%20Previous_ftimeLastOriginatingChange%20p=1%20%7C%20search%20(timeDelta%20%3C%20-2592000%20NOT%20(ObjectClass=%22container%22%20AND%20Name=%22Deleted%20Objects%22))%20%7C%20makemv%20pszLastOriginatingDsaDN%20delim=%22,CN=%22%20%7C%20eval%20OriginatingDC%20=%20mvindex(pszLastOriginatingDsaDN,%201,%201)%20%7C%20%20search%20$click.name2$%20=%20%22$click.value2$%22&earliest=0&latest=now

Possible metadata timestomping, usnLocalChange detection: No results

Schema and configuration partition suspicious modifications:

MITRE | ATT&CK T1098

Schema: SearchFlags or defaultSecurityDescriptor attributes | Configuration: RightsGuid, LocalizationDisplayId, DsHeuristics or tombstoneLifetime attributes index=$ad_index$ host=$domain_host$ sourcetype=adtimeline (pszAttributeName="SearchFlags" OR pszAttributeName="defaultSecurityDescriptor" OR pszAttributeName="RightsGuid" OR pszAttributeName="LocalizationDisplayId" OR pszAttributeName="DsHeuristics" OR pszAttributeName="tombstoneLifetime") dwVersion >= 2 | timechart span=1week count by pszAttributeName limit=0 0 toto if(isnull($row._time$),1,$row._time$) if(isnull($row._time$),now(),$row._time$ + $row._span$) search?q=index=$ad_index$%20host=$domain_host$%20sourcetype=adtimeline%20(pszAttributeName=%22SearchFlags%22%20OR%20pszAttributeName=%22defaultSecurityDescriptor%22%20OR%20pszAttributeName=%22RightsGuid%22%20OR%20pszAttributeName=%22LocalizationDisplayId%22%20OR%20pszAttributeName=%22DsHeuristics%22%20OR%20pszAttributeName=%22tombstoneLifetime%22)%20dwVersion%20%3E=%202%20%7C%20%20search%20%20pszAttributeName%20=%20%22$click.name2$%22&earliest=$drilldown.earliest$&latest=$drilldown.latest$

Schema and configuration partition suspicious modifications: No results

MITRE | ATT&CK T1114

Possible mail exfiltration on Exchange on prem msExchMRSRequest, msExchTransportRule and msExchPrivateMDB ObjectClass: index=$ad_index$ host=$domain_host$ sourcetype=adtimeline (ObjectClass=msExchMRSRequest AND pszAttributeName="isDeleted") OR (ObjectClass=msExchTransportRule AND pszAttributeName=msExchTransportRuleXml) OR (ObjectClass=msExchPrivateMDB AND pszAttributeName=nTSecurityDescriptor AND dwVersion >= 2 ) OR (ObjectClass=msExchRoleAssignment AND pszAttributeName=msExchRoleAssignmentFlags) | bucket span=1week _time | stats count by _time ObjectClass | where ObjectClass != "msExchRoleAssignment" OR (ObjectClass="msExchRoleAssignment" AND count < 50) | xyseries _time,ObjectClass,count 0 toto if(isnull($row._time$),1,$row._time$) if(isnull($row._time$),now(),$row._time$ + 604800) search?q=index=$ad_index$%20host=$domain_host$%20sourcetype=adtimeline%20(ObjectClass=msExchMRSRequest%20AND%20pszAttributeName=%22isDeleted%22)%20OR%20(ObjectClass=msExchTransportRule%20AND%20%20pszAttributeName=msExchTransportRuleXml)%20OR%20(ObjectClass=msExchPrivateMDB%20AND%20pszAttributeName=nTSecurityDescriptor%20AND%20dwVersion%20%3E=%202%20)%20OR%20(ObjectClass=msExchRoleAssignment%20AND%20%20pszAttributeName=msExchRoleAssignmentFlags)%20%20%7C%20%20search%20%20ObjectClass%20=%20%22$click.name2$%22&earliest=$drilldown.earliest$&latest=$drilldown.latest$

Possible mail exfiltration on Exchange on prem msExchMRSRequest, msExchTransportRule and msExchPrivateMDB ObjectClass: No results

© 2020 The MITRE Corporation. This work is reproduced and distributed with the permission of The MITRE Corporation.

================================================ FILE: SA-ADTimeline/default/data/ui/views/suspicious_exchange_activity.xml ================================================
| tstats latest(_time) where index=* by index true index index | tstats latest(_time) where index=$ad_index$ (sourcetype=adobjects OR sourcetype=gcobjects OR sourcetype=adtimeline) by host true host host Microsoft Exchange infrastructure: Microsoft Exchange schema information, rangeUpper attribute of ms-Exch-Schema-Version-Pt object: index=$ad_index$ host=$domain_host$ sourcetype=adobjects (ObjectClass=attributeSchema AND Name=ms-Exch-Schema-Version-Pt) | table Name | appendpipe [stats count | eval "Name"="Void" | where count=0 | table "Name"] | eval checkExch =case(Name == "ms-Exch-Schema-Version-Pt", "Exchange installed in the AD forest", 1=1 , "Exchange not installed in the AD forest") | fields checkExch $earliest$ $latest$ <br/> index=$ad_index$ host=$domain_host$ sourcetype=adobjects (ObjectClass=attributeSchema AND Name=ms-Exch-Schema-Version-Pt) | rex field=_raw "rangeUpper\">(?<rangeUpper>.+?)</I32>" | lookup ExchangeSchema_lookup rangeUpper AS rangeUpper OUTPUTNEW Exchange AS ExchangeV | stats count by ExchangeV, rangeUpper | rangemap field=rangeUpper low=15331-1000000 elevated=15312-15331 default=severe $earliest$ $latest$ Microsoft Exchange servers, msExchExchangeServer ObjectClass: index=$ad_index$ host=$domain_host$ sourcetype=adobjects ObjectClass=msExchExchangeServer | rex field=_raw "<S>Version (?<ExchVersion>.+?)</S>" | stats count by Name, ExchVersion, whenCreated | rename Name as "Exchange server name", ExchVersion as "Exchange server version", whenCreated as "Exchange server creation time" | table "Exchange server name", "Exchange server version", "Exchange server creation time" 0
<br/>
Possible mail exfiltration

MITRE | ATT&CK T1114

Exchange mailbox Forwarders, Transport rules and Remote Domain creation toto index=$ad_index$ host=$domain_host$ sourcetype=adtimeline pszAttributeName="msExchGenericForwardingAddress" OR "altRecipient" OR (ObjectCategory="CN=ms-Exch-Domain-Content-Config,CN=Schema,CN=Configuration,DC=labo,DC=local" AND pszAttributeName="whenCreated" ) OR (ObjectClass="msExchTransportRule" AND pszAttributeName="msExchTransportRuleXml") | timechart span=1week count by pszAttributeName limit=0 | rename whenCreated as RemoteDomainCreation -5y@h Accounts with forwarder attribute modified index=$ad_index$ host=$domain_host$ sourcetype=adtimeline pszAttributeName="altRecipient" OR pszAttributeName="msExchGenericForwardingAddress" | makemv delim=";" _raw | eval Value=mvindex(_raw,9) | sort -_time |rename Value as "Value (if altRecipient)" | table _time, DN, pszAttributeName, dwVersion, "Value (if altRecipient)" 0 case (like(value,"CN"), "#FE5D26"
Transport Rules forwarding messages index=$ad_index$ host=$domain_host$ sourcetype=adobjects [search index=$ad_index$ host=$domain_host$ sourcetype=adtimeline (ObjectClass=msExchTransportRule AND pszAttributeName=msExchTransportRuleXml) | table DN]| xpath outfield=WhenModified "//DT[@N='Modified']" | xpath outfield=whenCreated "//DT[@N='whenCreated']" | xpath outfield=transportRule "//S[@N='msExchTransportRuleXml']" | rex field=transportRule mode=sed "s/_x000D_|_x000A_|_x0009_//g" | xpath outfield=isActive field=transportRule "//@enabled" | xpath outfield=Recipient_address field=transportRule "//fork/recipient/@address" |xpath outfield=Action field=transportRule "//action/@name" |xpath outfield=Action_Detail field=transportRule "//action/@externalName" |xpath outfield=Action_Args field=transportRule "//argument/@*" | xpath outfield=Condition field=transportRule "//condition" | xpath outfield=Exception field=transportRule "//fork[@exception='true/]" |xpath outfield=Comments field=transportRule "//rule/@comments" |eval isActive=if(isnull(isActive),"true",isActive) |search Action IN (AddEnvelopeRecipient,RedirectMessage,ModerateMessageByUser,AddEnvelopeRecipient,AddToRecipient,AddCcRecipient,AddManagerAsRecipientType) |table WhenModified, whenCreated, Name, isActive, Recipient_address, Action, Action_Detail, Action_Args,Condition, Exception, Comments |sort -WhenModified 0
Remote Domains configuration details index=$ad_index$ host=$domain_host$ sourcetype=adobjects ObjectCategory="CN=ms-Exch-Domain-Content-Config,CN=Schema,CN=Configuration,*"| rex field=_raw "<DT N=\"Modified\">(?<Modified>.+?)<\/DT>"| table _time, whenCreated, Modified, Name, Owner, DN 0
Exchange mailbox Import, Export, Discovery (msExchMRSRequest) index=$ad_index$ host=$domain_host$ sourcetype=adtimeline ObjectClass=msExchMRSRequest AND (pszAttributeName="isDeleted" OR pszAttributeName="whenCreated") | timechart span=1week count by pszAttributeName limit=0 0 msExchMRSRequest details index=$ad_index$ host=$domain_host$ sourcetype=adobjects | search [search index=$ad_index$ host=$domain_host$ sourcetype=adtimeline ObjectClass=msExchMRSRequest AND (pszAttributeName="isDeleted" OR pszAttributeName="whenCreated")| eval temp=if(like(Name, "%DEL:%"), split(Name,":"), Name) | eval Object=if(mvcount(temp)=2,mvindex(temp,1),temp) | eval DN= "*" . Object . "*" | fields DN] | rex field=_raw "<DT N=\"Created\">(?<Created>.+?)<\/DT>" | rex field=_raw "<DT N=\"DisplayName\">(?<DisplayName>.+?)<\/DT>" | rex field=_raw "<S N=\"msExchMailboxMoveSourceUserLink\">(?<msExchMailboxMoveSourceUserLink>.+?)<\/S>" | rex field=_raw "<S N=\"msExchMailboxMoveFilePath\">(?<msExchMailboxMoveFilePath>.+?)<\/S>" | rex field=_raw "<S N=\"msExchMailboxMoveSourceMDBLink\">(?<msExchMailboxMoveSourceMDBLink>.+?)<\/S>" | rex field=_raw "<S N=\"msExchMailboxMoveTargetMDBLink\">(?<msExchMailboxMoveTargetMDBLink>.+?)<\/S>" | rex field=_raw "<S N=\"DistinguishedName\">(?<DistinguishedName>.+?)<\/S>" | table Created, DisplayName, msExchMailboxMoveSourceUserLink, msExchMailboxMoveFilePath, msExchMailboxMoveSourceMDBLink, msExchMailboxMoveTargetMDBLink, DistinguishedName | sort Created 0 case (like(value,"aspx"),"#E94F37" )
Persistence

MITRE | ATT&CK T1098

RBAC roles Editions index=$ad_index$ host=$domain_host$ sourcetype=adtimeline ObjectClass=msExchRoleAssignment AND pszAttributeName=msExchRoleAssignmentFlags | bucket span=1week _time | stats count by _time ObjectClass | where ObjectClass != "msExchRoleAssignment" OR (ObjectClass="msExchRoleAssignment" AND count < 50) | xyseries _time,ObjectClass,count 0 RBAC Details index=$ad_index$ sourcetype=adobjects ObjectClass=msExchRoleAssignment| rex field=_raw "<S N=\"msExchUserLink\">(?<msExchUserLink>.+?)<\/S>" | rex field=_raw "<S N=\"msExchRoleLink\">(?<msExchRoleLink>.+?)<\/S>" | rex field=_raw "<S N=\"msExchDomainRestrictionLink\">(?<msExchDomainRestrictionLink>.+?)<\/S>"| table _time, Name, msExchUserLink, msExchRoleLink, msExchDomainRestrictionLink | sort -_time 0 case (like(value,"UnScoped Role Management"), "#FE5D26" , like(value,"Role Management"), "#F2C078" , like(value,"Impersonation") , "#FAEDCA" , like(value,"Mailbox Search"),"#C1DBB3" , like(value,"Mailbox Search"),"#7EBC89" , like(value,"Mailbox Import Export"),"#E94F37")
msExch* object class ACLs Editions index=$ad_index$ host=$domain_host$ sourcetype=adtimeline (ObjectClass=msExch* AND pszAttributeName=nTSecurityDescriptor AND dwVersion >= 2 ) | bucket span=1week _time | stats count by _time ObjectClass | where ObjectClass != "msExchRoleAssignment" OR (ObjectClass="msExchRoleAssignment" AND count < 50) | xyseries _time,ObjectClass,count 0
MsExchangeSecurityGroups

MITRE | ATT&CK T1098

Timeline, MsExchangeSecurityGroups: index=$ad_index$ host=$domain_host$ sourcetype=adtimeline (pszAttributeName = member AND dwVersion != 0) OR (pszAttributeName = whenCreated) [search index=$ad_index$ host=$domain_host$ sourcetype=adobjects ObjectClass = "group" OU="Microsoft Exchange Security Groups" | table DN] | table _time, DN, pszAttributeName, Member, dwVersion, ftimeCreated, ftimeDeleted | sort -_time 0
Exchange security groups members: index=$ad_index$ host=$domain_host$ sourcetype=adobjects OU="Microsoft Exchange Security Groups" Members=* | rex field=Members mode=sed "s/<S>|<\/S>| //g" | table whenCreated, Name, Members | sort -whenCreated 0 case (match(value,"Organization Management"), "#FE5D26" , like(value,"Exchange Servers"), "#F2C078" , like(value,"Hygiene Management") , "#FAEDCA" , like(value,"Exchange Windows Permissions"),"#C1DBB3" , like(value,"Exchange Trusted Subsystem"),"#7EBC89" , like(value,"Server Management"),"#685044") case (match(value,"Organization Management"), "#FE5D26" , like(value,"Exchange Servers"), "#F2C078" , like(value,"Hygiene Management") , "#FAEDCA" , like(value,"Exchange Windows Permissions"),"#C1DBB3" , like(value,"Exchange Trusted Subsystem"),"#7EBC89" , like(value,"Server Management"),"#685044")
Phishing

MITRE | ATT&CK T1566

Transport Rules: track malicious disclaimer index=$ad_index$ host=$domain_host$ sourcetype=adobjects [search index=$ad_index$ host=$domain_host$ sourcetype=adtimeline (ObjectClass=msExchTransportRule AND pszAttributeName=msExchTransportRuleXml) | table DN]| xpath outfield=WhenModified "//DT[@N='Modified']" | xpath outfield=whenCreated "//DT[@N='whenCreated']" | xpath outfield=transportRule "//S[@N='msExchTransportRuleXml']" | rex field=transportRule mode=sed "s/_x000D_|_x000A_|_x0009_//g" | xpath outfield=isActive field=transportRule "//@enabled" | xpath outfield=Recipient_address field=transportRule "//fork/recipient/@address" |xpath outfield=Action field=transportRule "//action/@name" |xpath outfield=Action_Detail field=transportRule "//action/@externalName" |xpath outfield=Action_Args field=transportRule "//argument/@*" | xpath outfield=Condition field=transportRule "//condition" | xpath outfield=Exception field=transportRule "//fork[@exception='true/]" |xpath outfield=Comments field=transportRule "//rule/@comments" |eval isActive=if(isnull(isActive),"true",isActive) | search Action IN (ApplyHtmlDisclaimer) |table WhenModified, whenCreated, Name, isActive, Action, Action_Args,Condition, Exception, Comments |sort -WhenModified 0
Transport Rules: track SCL modifications index=$ad_index$ host=$domain_host$ sourcetype=adobjects [search index=$ad_index$ host=$domain_host$ sourcetype=adtimeline (ObjectClass=msExchTransportRule AND pszAttributeName=msExchTransportRuleXml) | table DN]| xpath outfield=WhenModified "//DT[@N='Modified']" | xpath outfield=whenCreated "//DT[@N='whenCreated']" | xpath outfield=transportRule "//S[@N='msExchTransportRuleXml']" | rex field=transportRule mode=sed "s/_x000D_|_x000A_|_x0009_//g" | xpath outfield=isActive field=transportRule "//@enabled" | xpath outfield=Recipient_address field=transportRule "//fork/recipient/@address" |xpath outfield=Action field=transportRule "//action/@name" |xpath outfield=Action_Detail field=transportRule "//action/@externalName" |xpath outfield=Action_Args field=transportRule "//argument/@*" | xpath outfield=Condition field=transportRule "//condition" | xpath outfield=Exception field=transportRule "//fork[@exception='true/]" |xpath outfield=Comments field=transportRule "//rule/@comments" |eval isActive=if(isnull(isActive),"true",isActive) | search (Action_Detail IN (SetScl) OR Action_Args IN(*SCL*)) |table WhenModified, whenCreated, Name, isActive, Action, Action_Args,Condition, Exception, Comments |sort -WhenModified 0

2020 The MITRE Corporation. This work is reproduced and distributed with the permission of The MITRE Corporation.

================================================ FILE: SA-ADTimeline/default/props.conf ================================================  [adtimeline] BREAK_ONLY_BEFORE_DATE = FIELD_DELIMITER = ; INDEXED_EXTRACTIONS = csv KV_MODE = none LINE_BREAKER = ([\r\n]+) NO_BINARY_CHECK = true SHOULD_LINEMERGE = false TZ = GMT MAX_DAYS_AGO = 10951 category = Structured disabled = false pulldown_type = true CHARSET = UTF-8 [adobjects] TRANSFORMS-adxml_remove_header = adxml_remove_header BREAK_ONLY_BEFORE = ^\s\s SHOULD_LINEMERGE = true LINE_BREAKER = ([\r\n]+) MAX_DAYS_AGO = 10951 NO_BINARY_CHECK = true TIME_FORMAT = %Y-%m-%dT%H:%M:%S%z TIME_PREFIX = createTimeStamp"> TRUNCATE = 100000000 category = Custom disabled = false pulldown_type = true CHARSET = UTF-8 BREAK_ONLY_BEFORE_DATE = EXTRACT-DN = (?.+?) EXTRACT-Name = (?.+?) EXTRACT-ObjectClass = (?.+?) EXTRACT-ObjectCategory = (?.+?) EXTRACT-SamAccountName = (?.+?) EXTRACT-SID = (?.+?) EXTRACT-AccessToString = (?.+?) EXTRACT-Owner = (?.+?) EXTRACT-Members = (?.+?) EXTRACT-userAccountControl = (?.+?) EXTRACT-lastLogonTimestamp = (?.+?) EXTRACT-DisplayName = (?.+?) EXTRACT-whenCreated =
(?.+?)
EXTRACT-dNSHostName = (?.+?) EXTRACT-SPNs = (?ms)servicePrincipalName.{1,100}(?.*?) EXTRACT-serviceBindingInformation = (?.+?) MAX_EVENTS = 4096 [gcobjects] TRANSFORMS-adxml_remove_header = adxml_remove_header BREAK_ONLY_BEFORE = ^\s\s SHOULD_LINEMERGE = true LINE_BREAKER = ([\r\n]+) MAX_DAYS_AGO = 10951 NO_BINARY_CHECK = true TIME_FORMAT = %Y-%m-%dT%H:%M:%S TIME_PREFIX =
TZ = GMT TRUNCATE = 100000000 category = Custom disabled = false pulldown_type = true CHARSET = UTF-8 BREAK_ONLY_BEFORE_DATE = EXTRACT-DN = (?.+?) EXTRACT-Name = (?.+?) EXTRACT-ObjectClass = (?.+?) EXTRACT-SamAccountName = (?.+?) EXTRACT-SID = (?.+?) EXTRACT-userAccountControl = (?.+?) EXTRACT-lastLogonTimestamp = (?.+?) EXTRACT-DisplayName = (?.+?) EXTRACT-whenCreated =
(?.+?)
EXTRACT-dNSHostName = (?.+?) EXTRACT-SPNs = (?ms)serviceprincipalname.{1,100}(?.*?) EXTRACT-serviceBindingInformation1 = (?ms)servicebindinginformation.{1,100}(?.*?) EXTRACT-serviceBindingInformation2 = (?.+?) EXTRACT-keywords1 = (?ms)keywords.{1,100}(?.*?) EXTRACT-keywords2 = (?.+?) MAX_EVENTS = 4096 ================================================ FILE: SA-ADTimeline/default/transforms.conf ================================================ [adxml_remove_header] REGEX = ^