### Installing Windows Server Backup Feature (PowerShell) Source: https://github.com/eshlomo1/microsoft-sentinel-secops/blob/master/Attack_IOC/PowerShell/ActiveDirectory/LearnActiveDirectoryMOL/Chapter13/CodeListing13.txt This snippet installs the Windows Server Backup feature on the server. It uses the Install-WindowsFeature cmdlet to install the necessary components for backup and recovery. Dependencies: Windows Server operating system. ```PowerShell Install-WindowsFeature -Name Windows-Server-Backup IncludeAllSubFeature ``` -------------------------------- ### Installing AD-Domain-Services PowerShell Source: https://github.com/eshlomo1/microsoft-sentinel-secops/blob/master/Attack_IOC/PowerShell/ActiveDirectory/LearnActiveDirectoryMOL/Chapter11/CodeListing11.txt This snippet installs the Active Directory Domain Services feature using PowerShell. The `-Confirm:$false` parameter suppresses the confirmation prompt. ```PowerShell Install-WindowsFeature -Name AD-Domain-Services -Confirm:$false ``` -------------------------------- ### Creating an RODC PowerShell Source: https://github.com/eshlomo1/microsoft-sentinel-secops/blob/master/Attack_IOC/PowerShell/ActiveDirectory/LearnActiveDirectoryMOL/Chapter11/CodeListing11.txt This snippet creates a Read-Only Domain Controller (RODC) account and then installs the RODC. It configures settings like the domain controller account name, replication source, and delegated administrator. ```PowerShell Add-ADDSReadOnlyDomainControllerAccount ` -SkipPreChecks ` -DomainControllerAccountName RODC1 ` -Credential (Get-Credential) -DomainName Manticore.org ` -SiteName Site1 ` -AllowPasswordReplicationAccountName ADMLrodc1 ` -DelegatedAdministratorAccountName dgreen ` -InstallDNS ` -ReplicationSourceDC server02.manticore.org ` -Force Install-ADDSDomainController -Credential (Get-Credential) ` -CriticalReplicationOnly:$false ` -DatabasePath "c:\windows\NTDS" -DomainName "manticore.org" ` -LogPath "C:\windows\NTDS" -SysvolPath "c:\windows\SYSVOL" ` -UseExistingAccount:$true -NoRebootOnCompletion:$false -Force ``` -------------------------------- ### Finding Global Catalogs (PowerShell) Source: https://github.com/eshlomo1/microsoft-sentinel-secops/blob/master/Attack_IOC/PowerShell/ActiveDirectory/LearnActiveDirectoryMOL/Chapter12/CodeListing12.txt This command retrieves the list of global catalogs in the Active Directory forest. `Get-ADForest` gets the forest object, and `-ExpandProperty GlobalCatalogs` extracts the list of global catalogs. ```PowerShell Get-ADForest | select -ExpandProperty GlobalCatalogs ``` -------------------------------- ### Get Replication Connections PowerShell Source: https://github.com/eshlomo1/microsoft-sentinel-secops/blob/master/Attack_IOC/PowerShell/ActiveDirectory/LearnActiveDirectoryMOL/Chapter17/CodeListing17.txt This command retrieves all Active Directory replication connections. It doesn't require any parameters and returns a list of replication connections in the Active Directory environment. ```PowerShell Get-ADReplicationConnection ``` -------------------------------- ### Retrieving Global Catalog Details (PowerShell) Source: https://github.com/eshlomo1/microsoft-sentinel-secops/blob/master/Attack_IOC/PowerShell/ActiveDirectory/LearnActiveDirectoryMOL/Chapter12/CodeListing12.txt This command retrieves the details (Name, Domain, and Site) of each global catalog in the Active Directory forest. It pipes the list of global catalogs to `Get-ADDomainController` to get the domain controller object for each, then selects the desired properties. ```PowerShell Get-ADForest | select -ExpandProperty GlobalCatalogs | foreach { Get-ADDomainController -Identity $_ | select Name, Domain, Site } ``` -------------------------------- ### Creating an Active Directory Group with PowerShell Source: https://github.com/eshlomo1/microsoft-sentinel-secops/blob/master/Attack_IOC/PowerShell/ActiveDirectory/LearnActiveDirectoryMOL/Chapter04/CodeListing04.txt This snippet creates a new Active Directory group named 'PStest' in the specified OU. It defines the group's scope as Global, category as Security, and sets a description. It requires the Active Directory module to be installed and imported. ```PowerShell New-ADGroup -Name PStest -Path "CN=Users,DC=Manticore,DC=org" -GroupCategory Security -GroupScope Global -Description "Test group for AD Lunches" ``` -------------------------------- ### Mount NTDSUtil Snapshot Source: https://github.com/eshlomo1/microsoft-sentinel-secops/blob/master/Attack_IOC/PowerShell/ActiveDirectory/LearnActiveDirectoryMOL/Chapter13/snapshot.txt This command mounts a specific NTDSUtil snapshot using its GUID. This allows access to the snapshot's data. ```text ntdsutil snapshot "mount 4f85522d-6d7b-42bc-be78-cd29585b7a20" quit quit ``` -------------------------------- ### Find Failed Logons on Detected Computers (KQL) Source: https://github.com/eshlomo1/microsoft-sentinel-secops/blob/master/Hunting/Password_Attack_ActiveDirectory.txt This query identifies accounts that failed to log on to computers where security detections were found. It first gets a list of computers with security detections and then finds failed logon events (EventID 4624) on those computers, summarizing the count by account. ```KQL //find which accounts failed to logon on computers where we identify a security detection let detections = toscalar(SecurityDetection | summarize makeset(Computer)); SecurityEvent | where Computer in (detections) and EventID == 4624 | summarize count() by Account ``` -------------------------------- ### Get Replication Up-To-Dateness Vector Table PowerShell Source: https://github.com/eshlomo1/microsoft-sentinel-secops/blob/master/Attack_IOC/PowerShell/ActiveDirectory/LearnActiveDirectoryMOL/Chapter17/CodeListing17.txt This command retrieves the Active Directory replication up-to-dateness vector table for a specified target server. The Target parameter specifies the server to check. ```PowerShell Get-ADReplicationUpToDatenessVectorTable -Target server02 ``` -------------------------------- ### Retrieving Azure AD Users with PowerShell Source: https://github.com/eshlomo1/microsoft-sentinel-secops/blob/master/Attack_IOC/PowerShell/ActiveDirectory/LearnActiveDirectoryMOL/Chapter22/CodeListing22.txt These snippets demonstrate various ways to retrieve users from Azure Active Directory using the Get-MsolUser cmdlet. Examples include retrieving all users, a specific user by UserPrincipalName, users based on enabled/disabled status, users in a specific city, state or country, and users based on a search string. ```PowerShell Get-MsolUser All ``` ```PowerShell Get-MsolUser UserPrincipalName robert@manticore.org ``` ```PowerShell Get-MsolUser EnabledFilter 'EnabledOnly' ``` ```PowerShell Get-MsolUser EnabledFilter 'DisabledOnly' ``` ```PowerShell Get-MsolUser City 'London' ``` ```PowerShell Get-MsolUser State 'Washington' ``` ```PowerShell Get-MsolUser Country 'US' ``` ```PowerShell Get-MsolUser SearchString 'Richard' ``` -------------------------------- ### Creating Starter GPOs Source: https://github.com/eshlomo1/microsoft-sentinel-secops/blob/master/Attack_IOC/PowerShell/ActiveDirectory/LearnActiveDirectoryMOL/Chapter08/CodeListing08.txt This snippet demonstrates how to create a new starter GPO using the `New-GPStarterGPO` cmdlet. This allows creating reusable templates for future GPO creation. ```PowerShell New-GPStarterGPO -Name ADMLstarterGPO2 -Comment "ADM Lunches starter GPO 2" ``` -------------------------------- ### Promoting a Domain Controller PowerShell Source: https://github.com/eshlomo1/microsoft-sentinel-secops/blob/master/Attack_IOC/PowerShell/ActiveDirectory/LearnActiveDirectoryMOL/Chapter11/CodeListing11.txt This snippet promotes a server to a domain controller using the `Install-ADDSDomainController` cmdlet. It sets various parameters such as database path, domain name, and site name. ```PowerShell Import-Module ADDSDeployment Install-ADDSDomainController ` -NoGlobalCatalog:$false ` -CreateDnsDelegation:$false ` -CriticalReplicationOnly:$false ` -DatabasePath "C:\Windows\NTDS" ` -DomainName "Manticore.org" ` -InstallDns:$true ` -LogPath "C:\Windows\NTDS" ` -NoRebootOnCompletion:$false ` -SiteName "Site1" ` -SysvolPath "C:\Windows\SYSVOL" ` -Force:$true ``` -------------------------------- ### Get AD User Group Memberships PowerShell Source: https://github.com/eshlomo1/microsoft-sentinel-secops/blob/master/Attack_IOC/PowerShell/ActiveDirectory/LearnActiveDirectoryMOL/Chapter05/CodeListing05.txt This snippet retrieves the group memberships of a specified Active Directory user. It gets the user's properties, selects the memberof property, and expands it to list all groups the user is a member of. ```PowerShell Get-ADUser -Identity mgreen -Properties memberof | select -ExpandProperty memberof ``` ```PowerShell Get-ADUser -Identity dgreen -Properties memberof | select -ExpandProperty memberof ``` -------------------------------- ### Creating a GPO with PowerShell Source: https://github.com/eshlomo1/microsoft-sentinel-secops/blob/master/Attack_IOC/PowerShell/ActiveDirectory/LearnActiveDirectoryMOL/Chapter08/CodeListing08.txt This snippet demonstrates how to create a new GPO using the `New-GPO` cmdlet from the `GroupPolicy` module. It shows creating an empty GPO with a specified name and comment, and creating a GPO from a starter GPO. ```PowerShell Import-Module GroupPolicy New-GPO -Name ADMLp1 -Comment "AD Lunches GPO" New-GPO -Name ADMLp2 -Comment "AD Lunches GPO from starter GPO" -StarterGpoName ADMLstarterGPO2 ``` -------------------------------- ### Joining a Machine to a Domain using PowerShell Source: https://github.com/eshlomo1/microsoft-sentinel-secops/blob/master/Attack_IOC/PowerShell/ActiveDirectory/LearnActiveDirectoryMOL/Chapter06/CodeListing06.txt This snippet joins a computer to the specified Active Directory domain and organizational unit (OU). It uses the `Get-Credential` cmdlet to prompt for user credentials, then uses the `Add-Computer` cmdlet with the provided credentials, domain name, OU path, and `-Force` parameter. Finally, it restarts the computer to complete the domain join process. ```powershell $cred = Get-Credential Add-Computer -Credential $cred -DomainName Manticore -OUPath "OU=Security Servers,OU=Servers,DC=Manticore,DC=org" -Force Restart-Computer ``` -------------------------------- ### Changing Active Directory Group Scope with PowerShell Source: https://github.com/eshlomo1/microsoft-sentinel-secops/blob/master/Attack_IOC/PowerShell/ActiveDirectory/LearnActiveDirectoryMOL/Chapter04/CodeListing04.txt These snippets modify the scope of existing Active Directory groups. The first two examples change the scope of 'ADL-group1' and 'ADL-group3' to Universal. The third example changes the scope of 'ADL-group3' to DomainLocal. Requires the Active Directory module. ```PowerShell Set-ADGroup -Identity ADL-group1 -GroupScope Universal ``` ```PowerShell Set-ADGroup -Identity ADL-group3 -GroupScope Universal ``` ```PowerShell Set-ADGroup -Identity ADL-group3 -GroupScope DomainLocal ``` -------------------------------- ### Unmount NTDSUtil Snapshot Source: https://github.com/eshlomo1/microsoft-sentinel-secops/blob/master/Attack_IOC/PowerShell/ActiveDirectory/LearnActiveDirectoryMOL/Chapter13/snapshot.txt This command unmounts a specific NTDSUtil snapshot using its GUID, releasing the resources associated with the mounted snapshot. ```text ntdsutil snapshot "unmount 4f85522d-6d7b-42bc-be78-cd29585b7a20" quit quit ``` -------------------------------- ### Creating an Active Directory Site (PowerShell) Source: https://github.com/eshlomo1/microsoft-sentinel-secops/blob/master/Attack_IOC/PowerShell/ActiveDirectory/LearnActiveDirectoryMOL/Chapter16/CodeListing16.txt This snippet shows how to create a new Active Directory site using the `New-ADReplicationSite` cmdlet. It sets the site name, description, accidental deletion protection, and other attributes like location. ```PowerShell New-ADReplicationSite -Name ADMLsite2 -Description "ADML test site 2" -ProtectedFromAccidentalDeletion $true -OtherAttributes @{Location = "Dallas"} ``` -------------------------------- ### User creation from a template using PowerShell Source: https://github.com/eshlomo1/microsoft-sentinel-secops/blob/master/Attack_IOC/PowerShell/ActiveDirectory/LearnActiveDirectoryMOL/Chapter02/CodeListing02.txt This script creates a new user in Active Directory, copying properties from an existing user (template). It first prompts for a password, retrieves an existing user's properties (memberof, office), and then creates the new user using the New-ADUser cmdlet with the -Instance parameter to copy the properties. ```PowerShell $secpass = Read-Host "Password" -AsSecureString $user = Get-ADUser -Identity jgreen -Properties memberof, office New-ADUser -Name "GREEN Bill" -SamAccountName bgreen -UserPrincipalName "bgreen@manticore.org" -AccountPassword $secpass -Path "cn=Users,dc=Manticore,dc=org" -Enabled:$true -Instance $user ``` -------------------------------- ### Analyzing Explicit Credentials Processes (KQL) Source: https://github.com/eshlomo1/microsoft-sentinel-secops/blob/master/Processes/Explicit_Credentials_Processes.txt This KQL query identifies processes using explicit credentials by analyzing Windows Security Event logs. It searches for Event ID 4648 (A logon was attempted using explicit credentials) within the last 7 days, summarizes the results by the 'Process' name, and then renders the data as a pie chart for visualization. ```KQL // Explicit credentials processes in specific time // Event ID 4648: A logon was attempted using explicit credentials SecurityEvent | where TimeGenerated > ago(7d) | where EventID == 4648 | summarize count() by Process | render piechart ``` -------------------------------- ### Managing RODC Password Policy PowerShell Source: https://github.com/eshlomo1/microsoft-sentinel-secops/blob/master/Attack_IOC/PowerShell/ActiveDirectory/LearnActiveDirectoryMOL/Chapter11/CodeListing11.txt These snippets demonstrate how to manage the RODC password replication policy using PowerShell. They include commands to get and set allowed and denied lists for password replication. ```PowerShell Get-ADDomainControllerPasswordReplicationPolicy -Identity RODC1 -Allowed Get-ADDomainControllerPasswordReplicationPolicy -Identity RODC1 -Denied Get-ADAccountResultantPasswordReplicationPolicy ` -DomainController RODC1 -Identity dgreen Allow Get-ADAccountResultantPasswordReplicationPolicy ` -DomainController RODC1 -Identity jbloggs DenyImplicit Add-ADDomainControllerPasswordReplicationPolicy -Identity RODC1 ` -AllowedList 'mgreen' Get-ADAccountResultantPasswordReplicationPolicy -DomainController RODC1 -Identity mgreen Allow ``` -------------------------------- ### DLL Loading with Specific Hashes - DeviceImageLoadEvents - KQL Source: https://github.com/eshlomo1/microsoft-sentinel-secops/blob/master/Attack_IOC/SolarwindsHack-IOCs/KQL Detections.txt This KQL query checks for DLL loading events involving files with specific SHA1 or SHA256 hashes within the DeviceImageLoadEvents table. It targets specific hashes known to be associated with malicious DLLs. ```KQL DeviceImageLoadEvents | where SHA1 in ("76640508b1e7759e548771a5359eaed353bf1eec","d130bd75645c2433f88ac03e73395fba172ef676","1acf3108bf1e376c8848fbb25dc87424f2c2a39c","e257236206e99f5a5c62035c9c59c57206728b28","6fdd82b7ca1c1f0ec67c05b36d14c9517065353b","2f1a5a7411d015d01aaee4535835400191645023","bcb5a4dcbc60d26a5f619518f2cfc1b4bb4e4387","16505d0b929d80ad1680f993c02954cfd3772207","d8938528d68aabe1e31df485eb3f75c8a925b5d9","395da6d4f3c890295f7584132ea73d759bd9d094","c8b7f28230ea8fbf441c64fdd3feeba88607069e","2841391dfbffa02341333dd34f5298071730366a","2546b0e82aecfe987c318c7ad1d00f9fa11cd305","2dafddbfb0981c5aa31f27a298b9c804e553c7bc","e2152737bed988c0939c900037890d1244d9a30e","fd15760abfc0b2537b89adc65b1ff3f072e7e31c") or SHA256 in ("32519b85c0b422e4656de6e6c41878e95fd95026267daab4215ee59c107d6c77","ce77d116a074dab7a22a0fd4f2c1ab475f16eec42e1ded3c0b0aa8211fe858d6","dab758bf98d9b36fa057a66cd0284737abf89857b73ca89280267ee7caf62f3b","eb6fab5a2964c5817fb239a7a5079cabca0a00464fb3e07155f28b0a57a2c0ed","ac1b2b89e60707a20e9eb1ca480bc3410ead40643b386d624c5d21b47c02917c","019085a76ba7126fff22770d71bd901c325fc68ac55aa743327984e89f4b0134","c09040d35630d75dfef0f804f320f8b3d16a481071076918e9b236a321c1ea77","0f5d7e6dfdd62c83eb096ba193b5ae394001bac036745495674156ead6557589","e0b9eda35f01c1540134aba9195e7e6393286dde3e001fce36fb661cc346b91d","20e35055113dac104d2bb02d4e7e33413fae0e5a426e0eea0dfd2c1dce692fd9","2b3445e42d64c85a5475bdbc88a50ba8c013febb53ea97119a11604b7595e53d","a3efbc07068606ba1c19a7ef21f4de15d15b41ef680832d7bcba485143668f2d","92bd1c3d2a11fc4aba2735d9547bd0261560fb20f36a0e7ca2f2d451f1b62690","a58d02465e26bdd3a839fd90e4b317eece431d28cab203bbdde569e11247d9e2","b8a05cc492f70ffa4adcd446b693d5aa2b71dc4fa2bf5022bf60d7b13884f666","cc082d21b9e880ceb6c96db1c48a0375aaf06a5f444cb0144b70e01dc69048e6","ffdbdd460420972fd2926a7f460c198523480bc6279dd6cca177230db18748e8") ``` -------------------------------- ### Enrichment for Hunting (KQL) Source: https://github.com/eshlomo1/microsoft-sentinel-secops/blob/master/Hunting/Storage/Monitor_KeyAccess.txt This section provides enrichment guidelines for threat hunting. It suggests mapping the 'WhoMade' field to the 'Account | Name' for user identification, 'CallerIpAddress' to 'IP | Address' for IP address tracking, and '_ResourceId' to 'Azure Resources | Resourceid' for resource identification. ```kql // Enrichment for Hunting // Account | Name = WhoMade // IP | Address = CallerIpAddress // Azure Reources | Resourceid = _ResourceId ``` -------------------------------- ### Get Replication Partner Metadata PowerShell Source: https://github.com/eshlomo1/microsoft-sentinel-secops/blob/master/Attack_IOC/PowerShell/ActiveDirectory/LearnActiveDirectoryMOL/Chapter17/CodeListing17.txt This command retrieves the Active Directory replication partner metadata for specified target servers. The Target parameter lists the servers to check, and PartnerType specifies the type of partner (both in this case). ```PowerShell Get-ADReplicationPartnerMetadata -Target server02, server03 -PartnerType both ``` -------------------------------- ### PostgreSQL Numeric Cast SQL Injection Source: https://github.com/eshlomo1/microsoft-sentinel-secops/blob/master/Stuff/si.txt This payload is specific to PostgreSQL. It uses the CHR function to build a string, and then attempts to cast the result to a numeric type. The conditional CASE WHEN is used similarly to the previous example, but relies on PostgreSQL syntax. ```SQL AND 3516=CAST((CHR(113)||CHR(106)||CHR(122)||CHR(106)||CHR(113))||(SELECT (CASE WHEN (3516=3516) THEN 1 ELSE 0 END))::text||(CHR(113)||CHR(112)||CHR(106)||CHR(107)||CHR(113)) AS NUMERIC) ``` -------------------------------- ### NTDSUtil Help Command Source: https://github.com/eshlomo1/microsoft-sentinel-secops/blob/master/Attack_IOC/PowerShell/ActiveDirectory/LearnActiveDirectoryMOL/Chapter13/snapshot.txt This command displays the help information for the ntdsutil snapshot functionality. It helps understand the available options and syntax for snapshot management. ```text ntdsutil snapshot help quit quit ``` -------------------------------- ### Getting Domain Controllers in an AD Site Source: https://github.com/eshlomo1/microsoft-sentinel-secops/blob/master/Attack_IOC/PowerShell/ActiveDirectory/LearnActiveDirectoryMOL/Chapter19/CodeListing19.txt This snippet retrieves a list of domain controllers within a specific Active Directory site. It first retrieves all computers within the 'Domain Controllers' OU, then filters the results to only include domain controllers in 'Site1'. ```PowerShell Get-ADComputer -SearchBase "OU=Domain Controllers,DC=Manticore,DC=org" -Filter * | foreach { Get-ADDomainController -Identity $_.DNSHostName } | where Site -eq 'Site1' ``` -------------------------------- ### Creating a Computer Account in Active Directory using PowerShell Source: https://github.com/eshlomo1/microsoft-sentinel-secops/blob/master/Attack_IOC/PowerShell/ActiveDirectory/LearnActiveDirectoryMOL/Chapter06/CodeListing06.txt This snippet creates a new, enabled computer account in Active Directory. It uses the `New-ADComputer` cmdlet with the `-Enabled`, `-Name`, `-Path`, and `-SamAccountName` parameters to define the account's properties and location within the directory. ```powershell New-ADComputer -Enabled $true -Name ADLComp3 -Path "CN=Computers,DC=Manticore,DC=org" -SamAccountName ADLCOMP3 ``` -------------------------------- ### Connecting to Azure AD with PowerShell Source: https://github.com/eshlomo1/microsoft-sentinel-secops/blob/master/Attack_IOC/PowerShell/ActiveDirectory/LearnActiveDirectoryMOL/Chapter22/CodeListing22.txt This snippet demonstrates how to connect to Azure Active Directory using PowerShell. It prompts the user for credentials and then uses the Connect-MsolService cmdlet to establish the connection. ```PowerShell $cred = Get-Credential Connect-MsolService Credential $cred ``` -------------------------------- ### Testing DNS Server Configuration Source: https://github.com/eshlomo1/microsoft-sentinel-secops/blob/master/Attack_IOC/PowerShell/ActiveDirectory/LearnActiveDirectoryMOL/Chapter15(DNS)/CodeListing15.txt This script retrieves network adapter configuration information and tests DNS resolution using different methods. ```PowerShell Get-WmiObject -Class Win32_NetworkAdapterConfiguration -Filter "IPenabled=$true" | select DNSDomain, DNSHostName, DNSServerSearchOrder ``` ```PowerShell Test-Connection -ComputerName 10.10.54.201 -Quiet ``` ```PowerShell Resolve-DnsName -Name $env:COMPUTERNAME -Server 10.10.54.201 ``` ```PowerShell Resolve-DnsName -Name 10.10.54.201 -Server 10.10.54.201 ``` -------------------------------- ### Filter Security Event Log for SPN Modification (Event 4742) Source: https://github.com/eshlomo1/microsoft-sentinel-secops/blob/master/Attack_IOC/ADHunting/ADF_Metadata_DCShadow.txt This command filters the Security event log for event ID 4742 to identify who modified a service principal name. It retrieves events that include a specific GUID associated with the DCShadow attack. ```PowerShell Get-EventLog -ComputerName "DC-Name" -LogName 'Security' -Message "*E3514235-4B06-11D1-AB04-00C04FC2DCD2*" -InstanceId 4742 | Format-List * ``` -------------------------------- ### Creating an Active Directory Site Link (PowerShell) Source: https://github.com/eshlomo1/microsoft-sentinel-secops/blob/master/Attack_IOC/PowerShell/ActiveDirectory/LearnActiveDirectoryMOL/Chapter16/CodeListing16.txt This snippet shows how to create a new Active Directory site link using the `New-ADReplicationSiteLink` cmdlet. It specifies the inter-site transport protocol, name, included sites, cost, replication frequency, and description. The `-PassThru` parameter returns the newly created object. ```PowerShell New-ADReplicationSiteLink -InterSiteTransportProtocol IP -Name 'ADMLsite1-ADMLsite2' -SitesIncluded ADMLsite1, ADMLsite2 -Cost 100 -ReplicationFrequencyInMinutes 180 -Description "Primary site link between ADMLsite1 and ADMLsite2" -PassThru ``` -------------------------------- ### Get AD User Details - PowerShell Source: https://github.com/eshlomo1/microsoft-sentinel-secops/blob/master/Attack_IOC/PowerShell/ActiveDirectory/LearnActiveDirectoryMOL/Chapter03/CodeListing03.txt This command retrieves the default properties of an Active Directory user object identified by their SamAccountName or Distinguished Name. It's often used to inspect user properties or as input for other commands. Requires the Active Directory PowerShell module. ```PowerShell Get-ADUser -Identity dgreen ``` -------------------------------- ### Creating a Windows Server Backup Policy (PowerShell) Source: https://github.com/eshlomo1/microsoft-sentinel-secops/blob/master/Attack_IOC/PowerShell/ActiveDirectory/LearnActiveDirectoryMOL/Chapter13/CodeListing13.txt This snippet creates a Windows Server Backup policy and configures it to back up specific volumes and system state. It uses several cmdlets from the WindowsServerBackup module to define the backup scope and target. Dependencies: Windows Server Backup feature, WindowsServerBackup module. ```PowerShell Import-Module WindowsServerBackup $wbpolicy = New-WBPolicy $volume = Get-WBVolume -VolumePath C: Add-WBVolume -Policy $wbpolicy -Volume $volume #3 Add-WBSystemState $wbpolicy Add-WBBareMetalRecovery $wbpolicy #3 $backupLocation = New-WBBackupTarget -VolumePath R: Add-WBBackupTarget -Policy $wbpolicy -Target $backupLocation #4 Set-WBVssBackupOptions -Policy $wbpolicy -VssCopyBackup Start-WBBackup -Policy $wbpolicy #5 ``` -------------------------------- ### Creating a new user with PowerShell Source: https://github.com/eshlomo1/microsoft-sentinel-secops/blob/master/Attack_IOC/PowerShell/ActiveDirectory/LearnActiveDirectoryMOL/Chapter02/CodeListing02.txt This snippet creates a new Active Directory user using the New-ADUser cmdlet. It prompts the user for a password, then sets the user's name, SamAccountName, UserPrincipalName, AccountPassword, Path (OU location), and enables the account. The -AsSecureString parameter ensures the password is handled securely. ```PowerShell $secpass = Read-Host "Password" -AsSecureString New-ADUser -Name "GREEN Dave" -SamAccountName dgreen -UserPrincipalName "dgreen@manticore.org" -AccountPassword $secpass -Path "cn=Users,dc=Manticore,dc=org" -Enabled:$true ``` -------------------------------- ### Creating an OU with PowerShell Source: https://github.com/eshlomo1/microsoft-sentinel-secops/blob/master/Attack_IOC/PowerShell/ActiveDirectory/LearnActiveDirectoryMOL/Chapter07/CodeListing07.txt This code creates a new Organizational Unit (OU) in Active Directory. It uses the `New-ADOrganizationalUnit` cmdlet to create an OU named 'ADML3' under the specified path. The `-ProtectedFromAccidentalDeletion` parameter is set to `$true` to prevent accidental deletion, and `-PassThru` returns the newly created object. ```powershell New-ADOrganizationalUnit -Name ADML3 -Path "DC=manticore,DC=org" -ProtectedFromAccidentalDeletion:$true -PassThru ``` -------------------------------- ### Get Active Directory Replication Metadata with PowerShell Source: https://github.com/eshlomo1/microsoft-sentinel-secops/blob/master/Attack_IOC/ADHunting/ADF_Membership.txt This command retrieves replication metadata for an Active Directory group using the `Get-ADReplicationAttributeMetadata` cmdlet. It requires the Active Directory module and a connection to a domain controller (`-Server localhost`). The output is displayed in an Out-GridView window. ```PowerShell Get-ADReplicationAttributeMetadata 'CN=Domain Admin,OU=Groups,DC=lab,DC=local' -Server localhost -ShowAllLinkedValues | Out-GridView ``` -------------------------------- ### Bulk Creation of OUs with CSV Source: https://github.com/eshlomo1/microsoft-sentinel-secops/blob/master/Attack_IOC/PowerShell/ActiveDirectory/LearnActiveDirectoryMOL/Chapter07/CodeListing07.txt This script imports OU data from a CSV file (`C:\Scripts\ADLunches\ous.txt`) and creates OUs in Active Directory based on the data in the CSV. The CSV file should contain columns named 'Name' and 'Path'. The `-ProtectedFromAccidentalDeletion` parameter is set to `$true` to prevent accidental deletion, and `-PassThru` returns the newly created object. ```powershell Import-Csv C:\Scripts\ADLunches\ous.txt | foreach { New-ADOrganizationalUnit -Name $_.Name -Path $_.Path -ProtectedFromAccidentalDeletion:$true -PassThru } ``` -------------------------------- ### Get User Last Logon Info (PowerShell) Source: https://github.com/eshlomo1/microsoft-sentinel-secops/blob/master/Attack_IOC/PowerShell/ActiveDirectory/LearnActiveDirectoryMOL/Chapter20/CodeListing20.txt This PowerShell command retrieves the last logon information for a specific Active Directory user (richard). It uses Get-ADUser to fetch the user object and then calculates LastLogonTimeStamp and LastLogon from FileTime values, displaying Name, LastLogonDate, LastLogonTimeStamp and LastLogon. ```PowerShell Get-ADUser -Identity richard -Properties * | select Name, LastLogonDate, @{N='LastLogonTimeStamp'; E={[DateTime]::FromFileTime([int64]::Parse($_.LastLogonTimeStamp))}}, @{N='LastLogon'; E={[DateTime]::FromFileTime([int64]::Parse($_.LastLogon))}} ``` -------------------------------- ### Get and Disable AD Account (Piped) - PowerShell Source: https://github.com/eshlomo1/microsoft-sentinel-secops/blob/master/Attack_IOC/PowerShell/ActiveDirectory/LearnActiveDirectoryMOL/Chapter03/CodeListing03.txt This command pipeline first retrieves an Active Directory user object and then pipes that object directly to the Disable-ADAccount cmdlet, disabling the account. This is an alternative way to specify the identity for commands that accept pipeline input. Requires the Active Directory PowerShell module. ```PowerShell Get-ADUser -Identity dgreen | Disable-ADAccount ``` -------------------------------- ### Create NTDSUtil Snapshot Source: https://github.com/eshlomo1/microsoft-sentinel-secops/blob/master/Attack_IOC/PowerShell/ActiveDirectory/LearnActiveDirectoryMOL/Chapter13/snapshot.txt This command creates a new snapshot of the Active Directory database. It activates the NTDS instance before creating the snapshot. ```text ntdsutil snapshot 'Activate Instance NTDS' Create quit quit ``` -------------------------------- ### Get Active Directory Replication Metadata (LastOriginatingDeleteTime) with PowerShell Source: https://github.com/eshlomo1/microsoft-sentinel-secops/blob/master/Attack_IOC/ADHunting/ADF_Membership.txt This command retrieves replication metadata, specifically examining the LastOriginatingDeleteTime, for an Active Directory group using the `Get-ADReplicationAttributeMetadata` cmdlet. It necessitates the Active Directory module and a link to a domain controller (`-Server localhost`). The output is shown in an Out-GridView window. ```PowerShell Get-ADReplicationAttributeMetadata 'CN=Domain Admin,OU=Groups,DC=lab,DC=local' -Server localhost -ShowAllLinkedValues | Out-GridView ``` -------------------------------- ### Adding Members to an Active Directory Group with PowerShell Source: https://github.com/eshlomo1/microsoft-sentinel-secops/blob/master/Attack_IOC/PowerShell/ActiveDirectory/LearnActiveDirectoryMOL/Chapter04/CodeListing04.txt These snippets add members to the 'ADL-group1' and 'PStest' Active Directory groups. They demonstrate adding members using distinguished name, LDAP filter, and filtering by property. Requires the Active Directory module. The last example for adding to PStest filters users with surname 'Green'. ```PowerShell Add-ADGroupMember -Identity ADL-group1 -Members "CN=GREEN Bill,CN=Users,DC=Manticore,DC=org" ``` ```PowerShell Add-ADGroupMember -Identity ADL-group1 -Members (Get-ADUser -LDAPFilter "(Name=Green Bill)") ``` ```PowerShell Add-ADGroupMember -Identity ADL-group1 -Members (Get-ADUser -Filter {Name -eq 'Green Bill'}) ``` ```PowerShell Add-ADGroupMember -Identity ADL-group1 -Members (Get-ADUser Get-ADUser Identity bgreen) ``` ```PowerShell Add-ADGroupMember -Identity PStest -Members (Get-ADUser -LDAPFilter "(sn=Green)") ``` -------------------------------- ### Adding A Record with PowerShell Source: https://github.com/eshlomo1/microsoft-sentinel-secops/blob/master/Attack_IOC/PowerShell/ActiveDirectory/LearnActiveDirectoryMOL/Chapter15(DNS)/CodeListing15.txt This command adds an A record to a DNS zone. The `-Name` parameter specifies the record name, `-ZoneName` specifies the zone name, `-IPv4Address` specifies the IP address, and `-ComputerName` specifies the DNS server. ```PowerShell Add-DnsServerResourceRecordA -Name "ADMLServer01" -ZoneName "admldns.test" -IPv4Address "192.168.175.54" -ComputerName server02 ``` -------------------------------- ### Copy AD User Group Memberships PowerShell Source: https://github.com/eshlomo1/microsoft-sentinel-secops/blob/master/Attack_IOC/PowerShell/ActiveDirectory/LearnActiveDirectoryMOL/Chapter05/CodeListing05.txt This snippet copies the group memberships from one Active Directory user account to another. It removes all existing group memberships of the target user and then adds the group memberships of the source user to the target user. It uses Get-ADUser to get the memberof properties, Remove-ADGroupMember to remove memberships and Add-ADGroupMember to add the memberships. ```PowerShell $target = Get-ADUser -Identity mgreen -Properties memberof foreach ($member in $target.memberof){ Remove-ADGroupMember -Identity $member -Members $target -Confirm:$false } $source = Get-ADUser -Identity dgreen -Properties memberof foreach ($member in $source.memberof){ Add-ADGroupMember -Identity $member -Members $target -Confirm:$false } ``` -------------------------------- ### Enabling PowerShell Remoting (WSMan) Source: https://github.com/eshlomo1/microsoft-sentinel-secops/blob/master/Attack_IOC/PowerShell/DSC/Demo_WindowServer2012R2/ReadMe.txt This command enables PowerShell remoting (WSMan) on a client machine, allowing remote management of the system. The -force parameter suppresses confirmation prompts. ```PowerShell Enable-PSRemoting -force ``` -------------------------------- ### Calculate and Get Privileged AD Principals PowerShell Source: https://github.com/eshlomo1/microsoft-sentinel-secops/blob/master/Attack_IOC/ADHunting/ADF_SID_GROUP.txt This PowerShell script calculates the SIDs of privileged users and groups in Active Directory, including Enterprise Admins, Domain Admins, the built-in Administrator group, and the default Administrator user. It then uses these SIDs to retrieve the corresponding Active Directory objects using `Get-ADGroup` and `Get-ADUser`, even if the names have changed. Requires the `ActiveDirectory` module. ```PowerShell Import-Module ActiveDirectory # Calculate the SIDs of the highest privileged Users and Groups $SID_GROUP_EA = [System.Security.Principal.SecurityIdentifier]"$((Get-ADDomain -Identity (Get-ADForest).Name).DomainSID)-519" $SID_GROUP_DA = [System.Security.Principal.SecurityIdentifier]"$((Get-ADDomain).DomainSID)-512" $SID_GROUP_AD = [System.Security.Principal.SecurityIdentifier]'S-1-5-32-544' $SID_USER_AD = [System.Security.Principal.SecurityIdentifier]"$((Get-ADDomain).DomainSID)-500" # Get each one of these Privileged Security Principals Get-ADGroup $SID_GROUP_EA -Properties * -Server (Get-ADForest).Name Get-ADGroup $SID_GROUP_DA -Properties * Get-ADGroup $SID_GROUP_AD -Properties * Get-ADUser $SID_USER_AD -Properties * ``` -------------------------------- ### Detect Vulnerable Azure Network Watcher VM Extensions Source: https://github.com/eshlomo1/microsoft-sentinel-secops/blob/master/Resource Graph Explorer/Az_Network_Watcher_VM.txt This Azure Resource Graph query identifies virtual machines (VMs) in Azure that have the 'AzureNetworkWatcherExtension' installed but not set to auto-upgrade to the latest minor version. It performs a left outer join to find VMs without the autoUpgradeMinorVersion property set to 'true'. The query returns VMs that may be vulnerable due to an outdated extension. ```Azure Resource Graph resources | where type == 'microsoft.compute/virtualmachines' | extend JoinID = toupper(id) | join kind=leftouter ( resources | where type == 'microsoft.compute/virtualmachines/extensions' | where name == "AzureNetworkWatcherExtension" and properties.autoUpgradeMinorVersion == false | extend VMId = toupper(substring(id, 0, indexof(id, '/extensions'))) ) on $left.JoinID == $right.VMId | extend ExtensionName = coalesce(name, "No Extension"), AutoUpgradeMinorVersion = coalesce(properties.autoUpgradeMinorVersion, "No Extension") | where AutoUpgradeMinorVersion != "No Extension" ``` -------------------------------- ### Creating an Active Directory Subnet (PowerShell) Source: https://github.com/eshlomo1/microsoft-sentinel-secops/blob/master/Attack_IOC/PowerShell/ActiveDirectory/LearnActiveDirectoryMOL/Chapter16/CodeListing16.txt This snippet shows how to create a new Active Directory subnet using the `New-ADReplicationSubnet` cmdlet. It sets the subnet name, location, description, and associates it with a specific site. It also demonstrates how to protect the object from accidental deletion. ```PowerShell New-ADReplicationSubnet -Name '10.10.56.0/24' -Location 'Dallas' -Description 'ADML site 2 subnet' -Site ADMLsite2 Get-ADReplicationSubnet -Identity '10.10.56.0/24' | Set-ADObject -ProtectedFromAccidentalDeletion $true ``` -------------------------------- ### Determining policies using PowerShell Source: https://github.com/eshlomo1/microsoft-sentinel-secops/blob/master/Attack_IOC/PowerShell/ActiveDirectory/LearnActiveDirectoryMOL/Chapter10/CodeListing10.txt This snippet demonstrates various methods to retrieve and display Fine-Grained Password Policies. It includes retrieving all policies, formatting the output to show name and AppliesTo attributes, sorting by precedence, and displaying complexity and lockout-related settings. It also lists the precedence and password attributes. ```PowerShell Get-ADFineGrainedPasswordPolicy -Filter * Get-ADFineGrainedPasswordPolicy -Filter * | Format-Table Name, AppliesTo AutoSize Get-ADFineGrainedPasswordPolicy -Filter * | sort Precedence | Format-Table Name, Precedence, ComplexityEnabled, Lockout* -AutoSize Get-ADFineGrainedPasswordPolicy -Filter * | sort Precedence | Format-Table Name, Precedence, ComplexityEnabled, *Password* -AutoSize ``` -------------------------------- ### Export Active Directory Logon Hours to CSV - PowerShell Source: https://github.com/eshlomo1/microsoft-sentinel-secops/blob/master/Attack_IOC/PowerShell/Adlogonhours.txt This PowerShell script reads a list of usernames from a text file, retrieves their Active Directory user properties (including logon hours), converts the logon hours into a more readable format, and then exports the converted data to a CSV file. The `Get-ADUser` cmdlet fetches user details, `Convert-ADLogonHours` converts the logon hours, and `Export-Csv` writes the results to a CSV file. The script requires the Active Directory module to be installed. ```PowerShell $users = Get-Content c:\userlist.txt $results=@() ForEach($PSItem in $users) { $results += ( Get-ADUser -Filter 'Name -like $PSItem' -Properties * |Convert-ADLogonHours -NoWarnings ) } $results | export-csv "adlogon.csv" -NoTypeInformation ``` -------------------------------- ### Detect ADFIND Enumeration using KQL Source: https://github.com/eshlomo1/microsoft-sentinel-secops/blob/master/General/ADFIND_Detects.txt This KQL query detects the execution of ADFIND enumeration commands. It searches for specific keywords in the ProcessCommandLine and verifies that the process path ends with '\adfind.exe'. The query leverages the DeviceProcessEvents table, focusing on processes initiated by ADFIND that perform common enumeration tasks. ```KQL DeviceProcessEvents | where ((ProcessCommandLine contains "objectcategory" or ProcessCommandLine contains "trustdmp" or ProcessCommandLine contains "dcmodes" or ProcessCommandLine contains "dclist" or ProcessCommandLine contains "domainlist" or ProcessCommandLine contains "computers_pwdnotreqd") and FolderPath endswith "\\adfind.exe") ``` -------------------------------- ### Creating a Sub-OU with PowerShell Source: https://github.com/eshlomo1/microsoft-sentinel-secops/blob/master/Attack_IOC/PowerShell/ActiveDirectory/LearnActiveDirectoryMOL/Chapter07/CodeListing07.txt This code creates a new Organizational Unit (OU) in Active Directory as a sub-OU. It uses the `New-ADOrganizationalUnit` cmdlet to create an OU named 'Chapter7' under the 'ADML3' OU. The `-ProtectedFromAccidentalDeletion` parameter is set to `$true` to prevent accidental deletion, and `-PassThru` returns the newly created object. ```powershell New-ADOrganizationalUnit -Name Chapter7 -Path "OU=ADML3,DC=manticore,DC=org" -ProtectedFromAccidentalDeletion:$true -PassThru ``` -------------------------------- ### SolarWinds Process Creation - DeviceProcessEvents - KQL Source: https://github.com/eshlomo1/microsoft-sentinel-secops/blob/master/Attack_IOC/SolarwindsHack-IOCs/KQL Detections.txt This KQL query checks for process creation events related to the SolarWinds BusinessLayerHost.exe, excluding specific legitimate SolarWinds processes. It aims to identify potentially malicious activity originating from the compromised SolarWinds executable. ```KQL DeviceProcessEvents | where InitiatingProcessFileName =~ "solarwinds.businesslayerhost.exe" | where not(FolderPath endswith @"\SolarWinds\Orion\APM\APMServiceControl.exe" or FolderPath endswith @"\SolarWinds\Orion\ExportToPDFCmd.Exe" or FolderPath endswith @"\SolarWinds.Credentials\SolarWinds.Credentials.Orion.WebApi.exe" or FolderPath endswith @"\SolarWinds\Orion\Topology\SolarWinds.Orion.Topology.Calculator.exe" or FolderPath endswith @"\SolarWinds\Orion\Database-Maint.exe" or FolderPath endswith @"\SolarWinds.Orion.ApiPoller.Service\SolarWinds.Orion.ApiPoller.Service.exe" or FolderPath endswith @"\Windows\SysWOW64\WerFault.exe") ``` -------------------------------- ### SolarWinds File System Events - DeviceFileEvents - KQL Source: https://github.com/eshlomo1/microsoft-sentinel-secops/blob/master/Attack_IOC/SolarwindsHack-IOCs/KQL Detections.txt This KQL query checks for file creation, modification, or other file system events initiated by the SolarWinds BusinessLayerHost.exe. It focuses on files with extensions like exe, dll, ps1, and jpg, which are commonly used by malware. ```KQL DeviceFileEvents | where InitiatingProcessFileName =~ "solarwinds.businesslayerhost.exe" | where FileName endswith "exe" or FileName endswith "dll" or FileName endswith "ps1" or FileName endswith "jpg" ``` -------------------------------- ### Discovering Domain Controllers by Service (PowerShell) Source: https://github.com/eshlomo1/microsoft-sentinel-secops/blob/master/Attack_IOC/PowerShell/ActiveDirectory/LearnActiveDirectoryMOL/Chapter12/CodeListing12.txt These commands discover domain controllers based on specific services they are running. Each command uses `-Discover` to find domain controllers providing PrimaryDC, GlobalCatalog, KDC, TimeService, ReliableTimeService, and ADWS services. ```PowerShell Get-ADDomainController -Discover -Service PrimaryDC ``` ```PowerShell Get-ADDomainController -Discover -Service GlobalCatalog ``` ```PowerShell Get-ADDomainController -Discover -Service KDC ``` ```PowerShell Get-ADDomainController -Discover -Service TimeService ``` ```PowerShell Get-ADDomainController -Discover -Service ReliableTimeService ``` ```PowerShell Get-ADDomainController -Discover -Service ADWS ``` -------------------------------- ### Viewing Active Directory Site Links (PowerShell) Source: https://github.com/eshlomo1/microsoft-sentinel-secops/blob/master/Attack_IOC/PowerShell/ActiveDirectory/LearnActiveDirectoryMOL/Chapter16/CodeListing16.txt This snippet demonstrates how to view Active Directory site links using the `Get-ADReplicationSiteLink` cmdlet. ```PowerShell Get-ADReplicationSiteLink ``` -------------------------------- ### Creating a New Azure AD User with PowerShell Source: https://github.com/eshlomo1/microsoft-sentinel-secops/blob/master/Attack_IOC/PowerShell/ActiveDirectory/LearnActiveDirectoryMOL/Chapter22/CodeListing22.txt This snippet shows how to create a new user in Azure Active Directory using the New-MsolUser cmdlet. It specifies the user principal name, display name, first name, last name, usage location, and license assignment. ```PowerShell New-MsolUser UserPrincipalName alex@manticore.org DisplayName 'Alex Skipton' -FirstName 'Alex' -LastName 'Skipton' -UsageLocation 'GB' LicenseAssignment 'Manticore:Standard' ``` -------------------------------- ### Detecting Brute Force Attack Patterns - KQL Source: https://github.com/eshlomo1/microsoft-sentinel-secops/blob/master/Hunting/BF.txt This KQL query for Microsoft Sentinel analyzes `syslogs_CL` data to detect potential brute force attacks. It defines thresholds, extracts numerous fields from the `RawData` string using `extend` and string manipulation functions, aggregates authentication attempts by time window using `summarize` based on success and failure counts, and filters results using `where` based on predefined failure and success count thresholds, finally expanding the results using `mvexpand` and mapping fields for entity recognition. ```KQL // Brute force attack let failureCountThreshold = 5; let successCountThreshold = 1; let timeRange = 1d; let authenticationWindow = 20m; syslogs_CL // table name | where TimeGenerated >= ago(10d) // time range // Extend Values // the log strcuture need the extend operator to calculated columns or append them to a specific result set // Each columns / field / value provide string for later user - a later use can print / project and use for other conditions | extend ExternalIPAddress = extract_all(@"((?:[0-9]{1,3}\.){3}[0-9]{1,3})", RawData)[1] | extend status=split(RawData, ' ')[10] | extend bytes_sent=split(RawData, ' ')[12] | extend request=split(RawData, ' ')[14] | extend request2=split(RawData, ' ')[15] // Extend Base64 // the based64 must be encoded to make sure we've got the addtional information | extend b64=split(base64_decode_tostring("eyJob3N0IjoiYmV0YW5s=="), '""') | extend host_ = tostring(b64[0].host) | extend blocked=split(RawData, ' ')[19] | extend block_reason=split(RawData, ' ')[20] | extend human=split(RawData, ' ')[21] | extend country_name=split(RawData, ' ')[25] | extend country_code=split(RawData, ' ')[27] | extend request_id=split(RawData, ' ')[29] | extend request_id=split(RawData, ' ')[31] | extend captured_vector=split(RawData, ' ')[33] | extend request_time=split(RawData, ' ')[35] | extend domain_name=split(RawData, ' ')[41] | extend referer=split(RawData, ' ')[45] | extend user_agent=split(RawData, ' ')[47] // Brute force information | summarize StartTimeUtc = min(TimeGenerated), EndTimeUtc = max(TimeGenerated), IPAddress = makeset(IPAddress), makeset(OS), makeset(Browser), makeset(City), makeset(ResultType), FailureCount = countif(FailureOrSuccess == "Failure"), SuccessCount = countif(FailureOrSuccess == "Success") by bin(TimeGenerated, authenticationWindow) //, UserDisplayName, UserPrincipalName, AppDisplayName | where FailureCount >= failureCountThreshold and SuccessCount >= successCountThreshold | mvexpand | extend IPAddress = tostring(IPAddress) | extend timestamp = StartTimeUtc, AccountCustomEntity = UserPrincipalName, IPCustomEntity = IPAddress ``` -------------------------------- ### Creating DNS Forward Zone with PowerShell Source: https://github.com/eshlomo1/microsoft-sentinel-secops/blob/master/Attack_IOC/PowerShell/ActiveDirectory/LearnActiveDirectoryMOL/Chapter15(DNS)/CodeListing15.txt This command creates a primary forward DNS zone. The `-Name` parameter specifies the zone name, `-ComputerName` specifies the DNS server, and `-ReplicationScope` defines the replication scope. ```PowerShell Add-DnsServerPrimaryZone -Name "admldns.test" -ComputerName server02 -ReplicationScope "Domain" -PassThru ``` -------------------------------- ### Linking GPO to OU with PowerShell Source: https://github.com/eshlomo1/microsoft-sentinel-secops/blob/master/Attack_IOC/PowerShell/ActiveDirectory/LearnActiveDirectoryMOL/Chapter09/CodeListing09.txt This snippet links an existing GPO to a specified Organizational Unit (OU) using the New-GPLink cmdlet. It retrieves the GPO by its name and then creates a link to the target OU. The target OU's distinguished name is required. ```PowerShell Get-GPO -Name ADMlgpo2 | New-GPLink -Target "OU=ADMLunches,DC=manticore,DC=org" ``` -------------------------------- ### Specific File Hash Search - All Device Events - KQL Source: https://github.com/eshlomo1/microsoft-sentinel-secops/blob/master/Attack_IOC/SolarwindsHack-IOCs/KQL Detections.txt This KQL query searches for a specific file hash across various device event tables (DeviceFileEvents, DeviceProcessEvents, DeviceEvents, DeviceRegistryEvents, DeviceNetworkEvents, DeviceImageLoadEvents). It identifies devices, actions, and files associated with the provided SHA1 hash, distinguishing between parent and child processes. ```KQL let fileHash = "e152f7ce2d3a4349ac472880c2caf8f72fac16ba"; find in (DeviceFileEvents, DeviceProcessEvents, DeviceEvents, DeviceRegistryEvents, DeviceNetworkEvents, DeviceImageLoadEvents) where SHA1 == fileHash or InitiatingProcessSHA1 == fileHash project DeviceName, ActionType, FileName, InitiatingProcessFileName, Timestamp, SHA1, InitiatingProcessSHA1 | project DeviceName, ActionType, Timestamp, FileName = iff(SHA1 == fileHash, FileName, InitiatingProcessFileName), MatchedSide=iff(SHA1 == fileHash, iff(InitiatingProcessSHA1 == fileHash, "Both", "Child"), "Parent") | summarize makeset(ActionType), FirstTimestamp=min(Timestamp), (LastTimestamp, LastActionType)=arg_max(Timestamp, ActionType) by FileName, MatchedSide, DeviceName | sort by DeviceName, LastTimestamp desc ``` -------------------------------- ### Finding Domain Controllers in Active Directory (PowerShell) Source: https://github.com/eshlomo1/microsoft-sentinel-secops/blob/master/Attack_IOC/PowerShell/ActiveDirectory/LearnActiveDirectoryMOL/Chapter12/CodeListing12.txt This command retrieves a list of all Active Directory domain controllers and displays their Name, Site, IPv4Address, IsGlobalCatalog, and IsReadOnly properties in a table format. The `-AutoSize` parameter ensures that the columns are automatically sized to fit the content. ```PowerShell Get-ADDomainController -Filter * | Format-Table Name, Site, IPv4Address, IsGlobalCatalog, IsReadOnly -AutoSize ``` -------------------------------- ### Calculate Billable Nodes Per Day - KQL Source: https://github.com/eshlomo1/microsoft-sentinel-secops/blob/master/Cost/Cost_By_Nodes.txt This KQL query filters logs based on time and type, then calculates the distinct count of billable computers per hour, subsequently aggregating this data to provide daily and monthly billable node counts. It filters out numerous event types and requires the `Computer`, `_IsBillable`, `Type`, and `TimeGenerated` fields to be present in the data. The final result is sorted by `billableNodesPerDay` in descending order. ```KQL find where TimeGenerated >= startofday(ago(31d)) and TimeGenerated < startofday(now()) project Computer, _IsBillable, Type, TimeGenerated | where Type !in ( "Perf", "Event", "DeviceEvents", " SecurityEvent", " DeviceNetworkEvents", "DeviceFileEvents", " DeviceProcessEvents", " DeviceFileCertificateInfo", " SecurityRegulatoryCompliance", "AADNonInteractiveUserSignInLogs", " AzureActivity", " DeviceRegistryEvents", " DeviceNetworkInfo", "ADCSV_CL", " AD_Metadata_CL", " DeviceImageLoadEvents", " Usage", " OfficeActivity", " Operation", " Heartbeat", " DeviceInfo", " DeviceLogonEvents", " SigninLogs", " DnsEvents", " SecurityBaseline", " UserPeerAnalytics", " AuditLogs", " SecurityRecommendation", " SecurityAlert", " UserAccessAnalytics", "SecurityIncident", " AADManagedIdentitySignInLogs", " ADDS_Metadata_CL", " SecureScores", " Update", " SecurityNestedRecommendation", " SecureScoreControls", " DnsInventory", " ProtectionStatus", "SecurityDetection", " AADServicePrincipalSignInLogs", " ComputerGroup", " UpdateSummary", " AD_Metadata1_CL", " SecurityBaselineSummary" ) | extend computerName = tolower(tostring(split(Computer, '.')[0])) | where computerName != "" | where _IsBillable == true | summarize billableNodesPerHour=dcount(computerName) by bin(TimeGenerated, 1h) | summarize billableNodesPerDay = sum(billableNodesPerHour)/24., billableNodeMonthsPerDay = sum(billableNodesPerHour)/24./31. by day=bin(TimeGenerated, 1d) | sort by billableNodesPerDay desc ```