PowerShell is an amazing tool for interrogating the configuration of Windows systems. This can be valuable for threat hunting: the process of searching through systems to identify attackers that have bypassed defenses. We can look for the common attacker persistence mechanisms deployed as Windows services, scheduled tasks, listening port numbers, new users added, and more.
If you are running PowerShell on a corporate system, some of the commands shown in this article could trigger alerts for attacker activity. Consider running the commands in this article on a non-corporate system, or you can use a free Windows 11 development virtual machine trial from Microsoft.
Let's try this out. Open a PowerShell session, and run Get-ScheduledTask:
PS C:\Users\Sec504> Get-ScheduledTask TaskPath TaskName State -------- -------- ----- \Agent Activation Runtime\ S-1-5-21-2977773840-2930198165... Disabled \Microsoft\Windows\.NET Framework\ .NET Framework NGEN v4.0.30319 Ready \Microsoft\Windows\.NET Framework\ .NET Framework NGEN v4.0.30319 64 Ready \Microsoft\Windows\.NET Framework\ .NET Framework NGEN v4.0.30319... Disabled \Microsoft\Windows\.NET Framework\ .NET Framework NGEN v4.0.30319... Disabled ...lots of scheduled tasks later \Microsoft\Windows\WwanSvc\ OobeDiscovery Ready \Microsoft\XblGameSave\ XblGameSaveTask Ready \Microsoft\XblGameSave\ XblGameSaveTaskLogon Ready PS C:\Users\Sec504>
Here's the problem: it can be hard to differentiate the normal from the malicious with any of these commands. Further, we know attackers will use naming conventions that blend into the system, making it difficult to spot something as out-of-place.
Differential analysis is the process of using baseline information about the configuration of a system, and comparing it to the current configuration. By using a known good baseline of a system, we can quickly spot any deviations to investigate as potentially suspicious.
To perform this type of analysis, we need the baseline, or the known-good configuration details. If you don't have this data in advance, sometimes it's possible to retroactively collect it using a gold image, the use it for comparison on the system being evaluated. Let's collect some baseline information to start. Open a PowerShell session on Windows, and run the following commands (cut and paste from the list below, or you can see the commands in context):
Set-Location $env:temp Get-Service | Select-Object -Property Name >baseline-services.txt Get-Scheduledtask | Select-Object TaskName > baseline-scheduledtasks.txt Get-NetTCPConnection -State Listen | Select-Object -Property LocalPort > baseline-tcplisteners.txt
Here are the commands in context with the shell prompt:
PS C:\Users\Sec504> Set-Location $env:temp PS C:\Users\Sec504\AppData\Local\Temp> Get-Service | Select-Object -Property Name >baseline-services.txt PS C:\Users\Sec504\AppData\Local\Temp> Get-Scheduledtask | Select-Object TaskName > baseline-scheduledtasks.txt PS C:\Users\Sec504\AppData\Local\Temp> Get-NetTCPConnection -State Listen | Select-Object -Property LocalPort > baseline-tcplisteners.txt PS C:\Users\Sec504\AppData\Local\Temp> Get-ChildItem -Name *.txt baseline-scheduledtasks.txt baseline-services.txt baseline-tcplisteners.txt
Here we collected baseline information for services, scheduled tasks, and TCP listeners. You could also collect baseline information for critical registry keys or files in a directory, for local users and groups, for group membership, and more!
Next, we'll create the "malicious" activity on the system for comparison. This is intended to simulate what an attacker could do after compromising a system.
NOTE: None of the actions here are malicious, and I'll show you how to remove them at the end of this article.
First, open a new PowerShell session as an administrator: right-click on Windows PowerShell, then select Run as administrator. This is needed to add a service as part of our malicious simulation.
Next, add a new service. We'll use the fictitious name Microsoft Dynamics to represent a quasi-normal service name that may escape casual inspection:
PS C:\WINDOWS\system32> New-Service -Name 'Windows Dynamics' -BinaryPathName 'C:\WINDOWS\System32\svchost.exe -k netsvcs' Status Name DisplayName ------ ---- ----------- Stopped Windows Dynamics Windows Dynamics
Next, add a new scheduled task:
$action = New-ScheduledTaskAction -Execute "$env:windir\system32\calc.exe" $trigger = New-ScheduledTaskTrigger -Daily -At 1am Register-ScheduledTask -TaskName 'Windows Dynamics Task' -Action $action -Trigger $trigger
Notice how 'Windows Dynamics Task' is in single quotes, but "$env:window\system32\calc.exe" is in double quotes? In PowerShell, variable expansion in a string only happens inside of double quotes. You could use double quotes for both examples, but I try to use single quotes where I can, and double quotes where I must.
Finally, start listening on TCP port 8888:
PS C:\WINDOWS\system32> $Listener = [System.Net.Sockets.TcpListener]8888 PS C:\WINDOWS\system32> $Listener.Start() PS C:\WINDOWS\system32>
Leave this PowerShell session running and return to the earlier non-administrative PowerShell session. We'll use differential analysis to identify the presence of the malicious simulation activity. Run the following commands, sending the output to files with the current prefix:
Set-Location $env:temp Get-Service | Select-Object -Property Name >current-services.txt Get-Scheduledtask | Select-Object TaskName > current-scheduledtasks.txt Get-NetTCPConnection -State Listen | Select-Object -Property LocalPort > current-tcplisteners.txt
Here are the commands in context with the shell prompt:
PS C:\Users\Sec504\AppData\Local\Temp> Set-Location $env:temp PS C:\Users\Sec504\AppData\Local\Temp> Get-Service | Select-Object -Property Name >current-services.txt PS C:\Users\Sec504\AppData\Local\Temp> Get-Scheduledtask | Select-Object TaskName > current-scheduledtasks.txt PS C:\Users\Sec504\AppData\Local\Temp> Get-NetTCPConnection -State Listen | Select-Object -Property LocalPort > current-tcplisteners.txt PS C:\Users\Sec504\AppData\Local\Temp> gci *.txt Directory: C:\Users\Sec504\AppData\Local\Temp Mode LastWriteTime Length Name ---- ------------- ------ ---- -a---- 6/23/2022 11:56 AM 16970 baseline-scheduledtasks.txt -a---- 6/23/2022 11:56 AM 22358 baseline-services.txt -a---- 6/23/2022 11:56 AM 520 baseline-tcplisteners.txt -a---- 6/24/2022 10:36 AM 17078 current-scheduledtasks.txt -a---- 6/24/2022 10:36 AM 22442 current-services.txt -a---- 6/24/2022 10:36 AM 542 current-tcplisteners.txt PS C:\Users\Sec504\AppData\Local\Temp>
Now we have both our baseline and our current files available for the list of services, scheduled tasks, and TCP listeners. We can quickly spot the differences that represent changes to the system using Compare-Object. Let's start with the service information. Establish the variables $baseline and $current for the two services lists with Get-Content:
PS C:\Users\Sec504\AppData\Local\Temp> $current = Get-Content .\current-services.txt PS C:\Users\Sec504\AppData\Local\Temp> $baseline = Get-Content .\baseline-services.txt PS C:\Users\Sec504\AppData\Local\Temp>
Next, compare the two objects to spot the changes:
PS C:\Users\Sec504\AppData\Local\Temp> Compare-Object $baseline $current InputObject SideIndicator ----------- ------------- Windows Dynamics => PS C:\Users\Sec504\AppData\Local\Temp>
Here we see a change between the baseline and the current files where the line Windows Dynamics is added to the current data (notice the SideIndicator column arrow is pointing to the right, representing the 2nd parameter in Compare-Object; in this case, added content to the $current data set).
Let's repeat these steps for the scheduled task information:
PS C:\Users\Sec504\AppData\Local\Temp> $current = Get-Content .\current-scheduledtasks.txt PS C:\Users\Sec504\AppData\Local\Temp> $baseline = Get-Content .\baseline-scheduledtasks.txt PS C:\Users\Sec504\AppData\Local\Temp> Compare-Object $baseline $current InputObject SideIndicator ----------- ------------- Windows Dynamics Task => PS C:\Users\Sec504\AppData\Local\Temp>
We can quickly spot the added scheduled task as well. Finally, look at the differences in the baseline and current TCP listeners:
PS C:\Users\Sec504\AppData\Local\Temp> $current = Get-Content .\current-tcplisteners.txt PS C:\Users\Sec504\AppData\Local\Temp> $baseline = Get-Content .\baseline-tcplisteners.txt PS C:\Users\Sec504\AppData\Local\Temp> Compare-Object $baseline $current InputObject SideIndicator ----------- ------------- 8888 => PS C:\Users\Sec504\AppData\Local\Temp>
When we have baseline information for comparison, differential analysis quickly identifies potential indicators of compromise. We can apply this analysis for any fairly consistent attribute on Windows, including:
- Local users (Get-LocalUser)
- Local groups (Get-LocalGroup)
- Members of local groups (Get-LocalGroupMember)
- Critical registry keys (Get-ChildItem, Get-ItemProperty)
- WMI events (Get-WMIObject -Namespace root\Subscription -Class __EventFilter)
- More!
Cleanup
Let's clean up the system to remove the simulated malicious activity. From the administrative PowerShell prompt, run the following commands:
PS C:\WINDOWS\system32> $Listener.Stop() PS C:\WINDOWS\system32> Unregister-ScheduledTask -TaskName 'Windows Dynamics Task' Confirm Are you sure you want to perform this action? Performing operation 'Delete' on Target '\Windows Dynamics Task'. [Y] Yes [A] Yes to All [N] No [L] No to All [S] Suspend [?] Help (default is "Y"): y PS C:\WINDOWS\system32> (Get-WmiObject -Class Win32_Service -Filter "Name='Windows Dynamics'").delete() __GENUS : 2 __CLASS : __PARAMETERS __SUPERCLASS : __DYNASTY : __PARAMETERS __RELPATH : __PROPERTY_COUNT : 1 __DERIVATION : {} __SERVER : __NAMESPACE : __PATH : ReturnValue : 0 PSComputerName : PS C:\WINDOWS\system32>
Confirm that you have successfully removed these elements from the system:
PS C:\WINDOWS\system32> Get-NetTCPConnection | Where-Object -Property LocalPort -EQ 8888 PS C:\WINDOWS\system32> Get-Service | Where-Object -Property DisplayName -EQ 'Windows Dynamics' PS C:\WINDOWS\system32> Get-ScheduledTask | Where-Object -Property TaskName -EQ 'Windows Dynamics Task' PS C:\WINDOWS\system32>
All these of these commands should return no output, confirming that you successfully removed the simulated malicious activity.
Summary
In this article we looked at the steps to apply differential analysis to identify threats in a Windows environment. Using baseline information we can quickly compare the known good elements of services, scheduled tasks, TCP listeners and more to the current configuration. PowerShell makes this straightforward, using Get-Service, Get-ScheduledTask, Get-NetTcpConnection and other commands, comparing the baseline to the current configuration with Compare-Object.
-Joshua Wright
Return to Getting Started With PowerShell
Joshua Wright is the author of SANS SEC504: Hacker Tools, Techniques, and Incident Handling, a faculty fellow for the SANS Institute, and a senior technical director at Counter Hack.