# Live Examination

## Examining Processes

To examine a live system, investigate running processes using PowerShell's `Get-Process` cmdlet. Running it without arguments displays information on active processes.

```powershell
PS C:\> Get-Process                  # Get brief information about running processes
```

<figure><img src="/files/DMHqyJIW3U6EoN3N7aip" alt=""><figcaption></figcaption></figure>

When you run `Get-Process`, it returns an object with both visible and hidden data. To access more information, you can use the pipe (`|`) to send the output to `Select-Object`, which allows you to display additional fields or all data using the asterisk (`*`) wildcard.

```powershell
PS C:\> Get-Process 'powersh*'                         # Get brief information about a named process with wildcard
PS C:\> Get-Process 'powershell' | Select-Object *     # Detailed information
```

<figure><img src="/files/kH2tuFCQ00NWagSfez9Y" alt=""><figcaption></figcaption></figure>

```powershell
PS C:\> Get-Process -ComputerName SEC504STUDENT        # Remote systems
```

<figure><img src="/files/hcXC4cHgN3pEr3tFTbAI" alt=""><figcaption></figcaption></figure>

```powershell
PS C:\> Get-Process | Select-Object -First 1 *
```

<figure><img src="/files/vLxafN5ja876dzQ1Ulop" alt=""><figcaption></figcaption></figure>

With PowerShell, cmdlets like `Get-Process` are useful but limited; they don't provide details such as the parent process ID or command line parameters, which are crucial for incident response. To access this information, you can use `Get-CimInstance`, which leverages the Windows Management Instrumentation (WMI) framework. By querying the `Win32_Process` class, you can retrieve detailed process information, including the process ID, name, and command line parameters.

```powershell
PS C:\> Get-CimInstance -Class Win32_Process | Select-Object ProcessId, ProcessName, CommandLine
```

<figure><img src="/files/j53yXFL4BvhlLdZV0gC9" alt=""><figcaption></figcaption></figure>

We can combine `Get-Process` with `Get-CimInstance` to obtain more details about a process. For example, we can use `Get-Process` to find the process ID for LSASS, then use `Get-CimInstance` to check for any unusual child processes linked to LSASS, which can indicate a security compromise.

```powershell
PS C:\> Get-Process 'lsass' | Select-Object -Property Id
```

<figure><img src="/files/Ikw69athw7i3sbnXONxM" alt=""><figcaption></figcaption></figure>

```powershell
PS C:\> Get-CimInstance -Class Win32_Process | Where-Object -Property ParentProcessId -EQ 716
```

<figure><img src="/files/6m6apPzQo4BduubU1gxZ" alt=""><figcaption></figcaption></figure>

TIP: Get-Process uses Id but Get-CimInstance uses ProcessId to refer to the same information.

<pre><code><strong>c:\> wmic process list brief
</strong></code></pre>

<figure><img src="/files/zoepDqUR2fMkpOd3Feca" alt=""><figcaption></figcaption></figure>

#### Basic Process Information

```
wmic process list brief                                               # List all running processes:
wmic process list full                                                # Detailed information about all processes
wmic process get name,processid,commandline                           # List processes with specific fields
wmic process where "name='notepad.exe'" get processid,commandline     # Find a specific process by name
wmic process where "ProcessId=8096" get name,executablepath           # Find a process by PID
wmic process where "processid=1234" call terminate                    # Kill a process by PID
wmic process where "name='notepad.exe'" call terminate                # Kill a process by name
```

### Identifying Suspicious Processes

* Is it a new or unrecognized process?
* Is the name random-looking?
* Is it running from a non-standard path?
* Is the parent suspicious?
* Is the parent-child relationship suspicious?
* Is it tied to suspicious activity?
* Base64 encoded command-line options?

Pay close attention to any running processes that have base64-encoded command-line options, especially PowerShell. Many attackers and malware authors use PowerShell's -EncodedCommand option to specify the content of a script to run at the command line. This way there are no extraneous .ps1 files left in the file system. Note that not every PowerShell script that uses `-EncodedCommand` is malicious, but they are worthy of further investigation.

## Examining Network Usage

For live Windows examination, checking current network usage is key. This involves identifying listening processes for inbound attacker connections or outbound connections to a C2 server. The PowerShell `Get-NetTCPConnection` cmdlet provides details on listening ports, established connections, and other network statuses, helping to investigate both inbound and outbound connections.

```powershell
PS C:\> Get-NetTCPConnection
```

<figure><img src="/files/9q1BQ1owLFWMdGAmt0Fy" alt=""><figcaption></figcaption></figure>

You can use `Get-NetTCPConnection` to filter connections by state (e.g., listening) and pipe it to `Select-Object` for specific details.

```powershell
PS C:\> Get-NetTCPConnection -State Listen | Select-Object -Property LocalAddress,LocalPort,OwningProcess
```

<figure><img src="/files/hn2AiJRYL3MShrVmBjhm" alt=""><figcaption></figcaption></figure>

The challenge with `Get-NetTCPConnection` is that it shows the process ID but not the process name. However, you can use `Get-Process -Id processid` to find the process name. Alternatively, you can combine both tasks into a single PowerShell command using a hash table with the `@{}` syntax.

```powershell
PS C:\> Get-NetTCPConnection | select local*,remote*,state,@{Name='Process';Expression={(Get-Process -Id
$_.OwningProcess).ProcessName}} | format-table
```

<figure><img src="/files/zdssR7zNXH4cHi6oQSUR" alt=""><figcaption></figcaption></figure>

Port 445 is listening on all interfaces: "::" for IPv6 and "0.0.0.0" for IPv4. The RemotePort is 0 because it doesn't apply to listening entries.

A service is listening on TCP port 9001, but it's restricted to the local IP address 127.0.0.1, meaning it's only accessible from the local system and not from any external systems.

Similar to identifying suspicious processes, there is no perfect list of suspicion indicators for identifying suspicious network traffic. With that in mind, here are some common things to consider:

* Any unusual network activity by a process, like Notepad connecting to port 80 multiple times or a service making repeated outbound connections, which could also be an automatic update service.
* Abnormal network activity for the environment, such as high activity during off-hours, long HTTP/HTTPS sessions, and frequent small outbound communications (beaconing).
* Unique indicators for specific techniques include lateral movement over SMB, which involves connections to SMB ports (TCP/UDP 135-139 and 445) on internal systems.
* Traffic to or from known malicious hosts, identified through threat intelligence or suspicious processes and connections.

## Examining Services

Another live examination task is to check Windows services, which are background tasks managed by the `services.exe` process and can be set to start automatically. Attackers often use these services for persistence to maintain access after a reboot. Use the PowerShell `Get-Service` cmdlet to view all running services or specify a service name for details.

```powershell
PS C:\> Get-Service
```

<figure><img src="/files/bbyucd5VhC5RB2u6X6BH" alt=""><figcaption></figcaption></figure>

```powershell
PS C:\> Get-Service FDResPub
```

<figure><img src="/files/dJ0E5MAt360oeFB8mBpN" alt=""><figcaption></figcaption></figure>

Get-Service doesn't show all details, like the program's path. To get this, use `Get-CimInstance -ClassName Win32_Service` for more service information.

<pre class="language-powershell"><code class="lang-powershell"><strong>PS C:\> Get-CimInstance -ClassName Win32_Service | Format-List
</strong>Name,Caption,Description,PathName
</code></pre>

<figure><img src="/files/Vavi3V5LGTbZHa8vkNkc" alt=""><figcaption></figcaption></figure>

## Registry Interrogation

PowerShell can query the Windows registry like a file system, treating top-level keys (e.g., HKEY\_LOCAL\_MACHINE, HKEY\_CURRENT\_USER) as drives, similar to how folders and drive letters are organized.

```powershell
PS C:\> Get-ChildItem 'HKLM:\SOFTWARE\Wow6432Node\Microsoft\Windows
\CurrentVersion\Uninstall\' | Select-Object PSChildName
```

<figure><img src="/files/wrODFiA6wmLNDxViX2J2" alt=""><figcaption></figcaption></figure>

```powershell
PS C:\> Get-ItemProperty 'HKLM:Software\Microsoft\Windows\CurrentVersion\Run'
```

<figure><img src="/files/4vv1bNWEb413b3gedB16" alt=""><figcaption></figcaption></figure>

To navigate registry keys, use `Get-ChildItem` (or `dir`) to list contents, or `Set-Location` (or `cd`) to change to a registry key location and list items from there.

```powershell
PS C:\> Set-Location 'HKLM:\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\'
```

<figure><img src="/files/YIUzqzerJxHjncNiR6eW" alt=""><figcaption></figcaption></figure>

## Unusual Accounts

During live examination, check local user accounts, as attackers may create new ones or add them to the Administrators group. Use the PowerShell cmdlet `Get-LocalUser` to list accounts, and pipeline it with `Where-Object` to filter by attributes, such as showing only enabled accounts with the `$True` variable.

```powershell
PS C:\> Get-LocalUser
```

<figure><img src="/files/oha8hSEIC1ATeVTv21Jp" alt=""><figcaption></figcaption></figure>

```powershell
PS C:\> Get-LocalUser | Where-Object -Property Enabled -EQ $true
PS C:\> Get-LocalUser | Where-Object { $_.Enabled -eq $true }
```

<figure><img src="/files/M3MQaRwALgGqeYNckI0f" alt=""><figcaption></figcaption></figure>

Similarly, the Get-LocalGroup will display all local groups on the Windows host. The Get- LocalGroupMember cmdlet will display the members of the specified group.

```powershell
PS C:\> Get-LocalGroup
```

<figure><img src="/files/5ZqD4vdroaqc9v8utROl" alt=""><figcaption></figcaption></figure>

```powershell
PS C:\> Get-LocalGroupMember Administrators
```

<figure><img src="/files/5FBW6IhdJponEZi3hQ9P" alt=""><figcaption></figcaption></figure>

## Unusual Scheduled Tasks

A common Windows investigation task is examining scheduled tasks, which run at set intervals, specific times, or after certain events, like login failures. Attackers may use scheduled tasks for persistence, often giving them unusual names or disguising them with legitimate software names to blend into the system.

```powershell
PS C:\> Get-ScheduledTask
```

<figure><img src="/files/sYqItXKKtiw2oeKtQ3I1" alt=""><figcaption></figcaption></figure>

<pre class="language-powershell"><code class="lang-powershell"><strong>PS C:\> Export-ScheduledTask -TaskName 'SR' -TaskPath \Microsoft\Windows\SystemRestore\
</strong></code></pre>

<figure><img src="/files/Jl8F6WqWVQO8CuedoTJg" alt=""><figcaption></figcaption></figure>

```powershell
PS C:\> Get-ScheduledTaskInfo -TaskName 'SR' -TaskPath \Microsoft\Windows\SystemRestore\
PS C:\> Get-ScheduledTaskInfo -TaskName 'SR' -TaskPath \Microsoft\Windows\SystemRestore\ | Select-Object LastRunTime
```

<figure><img src="/files/fwdBfjpaWobobZBirKcj" alt=""><figcaption></figcaption></figure>

The `Get-ScheduledTask` cmdlet doesn't show full details like the executed command or its arguments. To get these, use `Export-ScheduledTask` to export the task in XML format. For information on the last run time of a task, use `Get-ScheduledTaskInfo` to check the `LastRunTime`, `NextRunTime`, and `LastTaskResult` properties.

## Unusual Log Entries

You can use the `Get-WinEvent` cmdlet in PowerShell to examine Windows Event Logs. It replaces the older `Get-EventLog` cmdlet. By specifying an event log name, `Get-WinEvent` displays a summary of events, and with filtering, you can narrow down the analysis to specific date ranges or log resources.

<pre class="language-powershell"><code class="lang-powershell"><strong>PS C:\> $start = Get-Date 8/23/2024;
</strong>PS C:\> $end = Get-Date 8/25/2024;
PS C:\> Get-WinEvent -FilterHashtable @{LogName='Security'; StartTime=$start; EndTime=$end;}
</code></pre>

<figure><img src="/files/lWRnMSiarCE6NyJNX6T1" alt=""><figcaption></figcaption></figure>

`Get-WinEvent` allows filtering by Event Log name using `-LogName`, and specific events can be displayed with `Where-Object`. While both `Where-Object` and `FilterHashtable` can be used, `FilterHashtable` is generally faster.

```powershell
PS C:\> Get-WinEvent -LogName System | Where-Object -Property Id -EQ 7045 |
Format-List -Property TimeCreated,Message
```

<figure><img src="/files/91Um2IbMtWBOsvrBDMtA" alt=""><figcaption></figcaption></figure>

In these examples we investigate the System and the Security Event Logs, but Windows records a lot of detail in other Event Logs as well. We can run `Get-WinEvent -Listlog * | Select LogName, RecordCount` to get a list of all Event Logs on the system and the number of records in each log.

<figure><img src="/files/Bnz1TFuMJWIKd4zYoqgJ" alt=""><figcaption></figcaption></figure>

## Differential Analysis

During live examinations, the vast amount of data, such as services, processes, scheduled tasks, and network connections, can be overwhelming. Differential analysis helps by comparing the current system to a baseline configuration (like the original gold image) to narrow down the investigation.

```powershell
PS C:\> Get-Service > baseline-services-20220325.txt
```

<figure><img src="/files/3OZYZpHoF0dZCRluKYwU" alt=""><figcaption></figcaption></figure>

```powershell
PS C:\> Get-Service > services-liveinvestigation.txt
PS C:\> $baseline = Get-Content .\baseline-services-20220325.txt
PS C:\> $current = Get-Content .\services-liveinvestigation.txt
PS C:\> Compare-Object -ReferenceObject $baseline -DifferenceObject $current
```

<figure><img src="/files/Auzg9fWVQTHYb6eFESiV" alt=""><figcaption></figcaption></figure>

In this example, we use `Get-Service` to collect a list of services, saving the output to `baseline-services-20220325.txt`. During an investigation, we run the same command and save it to `services-liveinvestigation.txt`. Then, we load both files into PowerShell objects `$baseline` and `$current` using `Get-Content`, and compare them with `Compare-Object`, using `-ReferenceObject` for the baseline and `-DifferenceObject` for the investigation data.

The output of `Compare-Object` lets us quickly identify configuration changes between the gold image and the system under investigation.

## PowerShell Cheat Sheet

Conduct a ping sweep:

```powershell
PS C:\> 1..255 | % {echo "10.10.10.$_";ping -n 1 -w 100 10.10.10.$_ | Select-String ttl}
```

Conduct a por t scan:

```powershell
PS C:\> 1..1024 | % {echo ((new-object
Net.Sockets.TcpClient).Connect("10.10.10.10",$_)) "Port $_ is
open!"} 2>$null
```

Fetch a file via HTTP (wget in PowerShell):

```powershell
PS C:\> (New-Object
System.Net.WebClient).DownloadFile("http://10.10.10.10/nc.exe","
nc.exe")
```

Find all files with a par ticular name:

```powershell
PS C:\> Get-ChildItem "C:\Users\" -recurse -include
*passwords*.txt
```

Get a listing of all installed Microsoft Hotfixes:

```powershell
PS C:\> Get-HotFix
```

Navigate the Windows registry:

```powershell
PS C:\> cd HKLM:\
PS HKLM:\> ls
```

List programs set to start automatically in the registry:

```powershell
PS C:\> Get-ItemProperty HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\run
```

| Functionality        | PowerShell           | Legacy Command     |
| -------------------- | -------------------- | ------------------ |
| List processes       | Get-Process          | wmic.exe process   |
| Network connections  | Get-NetTCPConnection | netstat.exe -nao   |
| List services        | Get-Service          | sc.exe query       |
| Registry access      | Get-ChildItem        | reg.exe            |
| List users           | Get-LocalUser        | net.exe user       |
| List groups          | Get-LocalGroup       | net.exe localgroup |
| List scheduled tasks | Get-ScheduledTask    | schtasks.exe       |
| Access Event Logs    | Get-WinEvent         | wevtutil.exe       |
| Identify differences | Compare-Object       | fc.exe             |

It's OK to continue using legacy commands to get the information you need to complete your analysis! When invoking legacy commands, specify .exe at the end of the command to avoid using PowerShell aliases with the same name.

## Additional Supporting Tools

The Sysinternals tools are excellent (and free!):

* **Process Explorer**: Incredibly detailed information for running processes.
* **Process Monitor**: Shows file system, registry, network, and process information in real time.
* **TCPView**: Maps listening and active TCP and UDP activity to the associated applications.
* **Autoruns**: Displays a comprehensive list of Autostart Extensibility Points (ASEP).
* **Sysmon**: Collects detailed event information for system monitoring and analysis.
* **Procdump**: CLI tool to capture memory for a running process for analysis.

## Lab 1.1: Live Windows Examination

Identify the PowerShell commands that will allow you to examine various aspects of a system and nd signs of a possible compromise. Make sure to include commands that will:

* Show what programs are running
* Show listening ports
* Show what accounts exist on the system
* Show what groups exist, and which accounts are in each group
* Show what network shares are available
* Identify registry keys associated with Auto Start Extensibility
* Identify interesting files

### Process Enumeration

Let's look at the running processes by invoking the Get-Process command, as shown here.

```powershell
Get-Process
```

<figure><img src="/files/X6axpUFiCM6b9uoFlIuO" alt=""><figcaption></figcaption></figure>

* Handles : A count of handles (open les, sockets, and pipe resources)
* NPM(K) : The amount of non-paged memory the process is using in kilobytes
* PM(K) : The amount of paged memory the process is using in kilobytes
* WS(K) : The process working set size (the total amount of memory allocated to a process) in kilobytes
* CPU(s) : The amount of processor time that the process has used on all processors, in seconds
* Id : The unique identier for a process so that the system can reference it by the numeric value, also known as a PID
* ProcessName : The process name, often the executable name

```powershell
Get-Process lsass
```

<figure><img src="/files/5PQ6kyjBpkPgqqskbsOG" alt=""><figcaption></figcaption></figure>

We can also get more information about the process than the default columns displayed.

```powershell
Get-Process lsass | Select-Object -Property *
```

<figure><img src="/files/FiY8WdtKhxjRY9CHm2MB" alt=""><figcaption></figcaption></figure>

In this command, we requested only three specific fields; Path, Name, and Id (process ID) instead of all properties as in the previous `Get-Process` command, making it more manageable to view.

```powershell
Get-Process | Select-Object -Property Path, Name, Id
```

<figure><img src="/files/tpNqNZ8GrV18Pj0vffbW" alt=""><figcaption></figcaption></figure>

```powershell
Get-Process | Select-Object -Property Path, Name, Id | Where-Object -Property Name -EQ explorer
```

<figure><img src="/files/JmHFxoVq9S7zxh1G8Ie0" alt=""><figcaption></figcaption></figure>

We can use `Where-Object` to filter `Get-Process` output for potential IOCs, such as processes running from temporary directories, which is often a sign of malicious activity rather than normal system use.

```powershell
Get-Process | Select-Object -Property Path, Name, Id | Where-Object -Property Path -Like "*temp*"
```

<figure><img src="/files/NzvqzQu0t0GPiHSmaK2B" alt=""><figcaption></figcaption></figure>

In this output we've identied a suspicious process: **calcache** . It's possible the process could be legitimate though, so let's continue our analysis to investigate other factors as well

### Network Enumeration

In the previous section, we explored running processes; now we will examine the network listeners and connections on this host.

```powershell
Get-NetTCPConnection
```

<figure><img src="/files/tq7VWLXlZ2AUw5Bh7ztT" alt=""><figcaption></figcaption></figure>

The command output is too broad to view easily. Let's use a technique similar to what we used with Get-Process to show only the LocalAddress, LocalPort, State, and OwningProcess fields.

```powershell
Get-NetTCPConnection | Select-Object -Property LocalAddress, LocalPort, State, OwningProcess
```

<figure><img src="/files/gXT7keOHHrxcvWrzhiw7" alt=""><figcaption></figcaption></figure>

Several processes are listening for connections on the local system. One process is listening on all interfaces (local address 0.0.0.0) and is using an uncommon Windows port number: 4444.

The process ID for TCP port 4444 is 4380. We know the process ID, but not the process name. We can return to the Get-Process command to display the process details for this process ID.

```powershell
PS C:\Tools\LiveInvestigation> Get-Process | Select-Object -Property
Path, Name, Id | Where-Object -Property Id -eq 4380
```

<figure><img src="/files/bpz2WRPetEBPJF61RRL4" alt=""><figcaption></figcaption></figure>

The calcache process is back and listening on TCP port 4444. Let's terminate it.

```powershell
PS C:\Tools\LiveInvestigation> Get-Process | Select-Object -Property
Path, Name, Id | Where-Object -Property Id -eq 4380 | Stop-Process

PS C:\Tools\LiveInvestigation> Get-Process calcache
```

<figure><img src="/files/0h6RDGAtVHwYmmRsBvP9" alt=""><figcaption></figcaption></figure>

We still need to figure out how the attacker started the suspicious process. Let's keep examining autostart locations in the Windows registry.

### Registry Startup Keys

A common way to start a process automatically is by adding a registry value to the Windows Run or RunOnce keys, known as Autostart Extensibility Points (ASEPs). These keys initiate processes when the system boots or a user logs in. Windows supports several ASEP registry keys, with four being particularly common:

* HKEY\_LOCAL\_MACHINE\Software\Microsoft\Windows\CurrentVersion\Run
* HKEY\_LOCAL\_MACHINE\Software\Microsoft\Windows\CurrentVersion\RunOnce
* HKEY\_CURRENT\_USER\Software\Microsoft\Windows\CurrentVersion\Run
* HKEY\_CURRENT\_USER\Software\Microsoft\Windows\CurrentVersion\RunOnce

Using PowerShell, we can use the Get-ChildItem command to enumerate registry keys, and the Get-ItemProperty command to enumerate registry values in a specic key.

```powershell
Get-ChildItem HKCU:
```

<figure><img src="/files/fzXHxSuQzSLIhlgtmaDa" alt=""><figcaption></figcaption></figure>

In this output we see the Name column, which will be registry keys, and the Property column, which will be registry values in the top-level keys for the HKEY\_CURRENT\_USER hive (abbreviated HKCU ).

```powershell
Get-ItemProperty "HKLM:\Software\Microsoft\Windows\CurrentVersion\Run"
```

<figure><img src="/files/32v7kirk9UaEphViPwAM" alt=""><figcaption></figcaption></figure>

```powershell
Get-ItemProperty "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce"
```

<figure><img src="/files/nMoLOs13aWUA3s8MUNwY" alt=""><figcaption></figcaption></figure>

```powershell
Get-ItemProperty "HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Run"
```

<figure><img src="/files/bV9BPwh8htgyd28tzfl3" alt=""><figcaption></figcaption></figure>

```powershell
Get-ItemProperty "HKCU:\Software\Microsoft\Windows\CurrentVersion\RunOnce"
```

<figure><img src="/files/ZMVkLbkOuIeiloKRdPdk" alt=""><figcaption></figcaption></figure>

The output shows no registry values in the RunOnce keys, but both HKLM and HKCU Run keys have values. The HKLM Run key includes two programs (SecurityHealth and VMware User Process) with associated property values.

For the HKCU Run command we see an entry for **Calcache**, which corresponds to the **Calcache** process we identified earlier.

Let's remove the Calcache value from the Run key using `Remove-ItemProperty`.

```powershell
Remove-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Run" -Name "Calcache"
Get-ItemProperty "HKCU:\Software\Microsoft\Windows\CurrentVersion\Run\Calcache"
```

<figure><img src="/files/wnqg36FWMEJlY1XDTxPr" alt=""><figcaption></figcaption></figure>

Next,  let's remove the calcache.exe program as shown here.

```powershell
Remove-Item $env:temp\calcache.exe
Get-ChildItem $env:temp\calcache.exe
```

<figure><img src="/files/w3KYrd99jukTf09wGRZc" alt=""><figcaption></figcaption></figure>

### Differential Analysis

The analysis is progressing well, but attackers have multiple ways to deploy malware. We need to establish a baseline for comparison to assess the current environment.

There are three baseline files for services, scheduled tasks, and local users are stored in the `C:\Tools\LiveInvestigation\baseline` folder. Let’s review them.

```powershell
Get-ChildItem baseline
```

<figure><img src="/files/pHKI5hUWBEuZCGB2NJJI" alt=""><figcaption></figcaption></figure>

These three files are generated with the following commands.

```powershell
Get-Service | Select-Object -ExpandProperty Name | Out-File "baseline/services.txt"
Get-ScheduledTask | Select-Object -ExpandProperty TaskName | Out-File "baseline/scheduledtasks.txt"
Get-LocalUser | Select-Object -ExpandProperty Name | Out-File "baseline/localusers.txt"
```

Let’s use the same commands to get the current services, scheduled tasks, and local users.

<figure><img src="/files/pdmUUd5bXOA64tB2O9ns" alt=""><figcaption></figcaption></figure>

Next, we'll compare the newly-generated output to the baseline information.

### Services Differential Analysis

<pre class="language-powershell"><code class="lang-powershell">$servicesnow = Get-Content .\services.txt
$servicesbaseline = Get-Content baseline\services.txt
<strong>
</strong><strong>Compare-Object $servicesbaseline $servicesnow
</strong></code></pre>

<figure><img src="/files/SkGvAcD7yzgZVXRU4KvL" alt=""><figcaption></figcaption></figure>

The `Compare-Object` output shows a new service, **Dynamics**. While it might be suspicious like the **Calcache** process, we need to further investigate to determine if it's malicious.

### Users Differential Analysis

Let’s repeat this process, using differential analysis to evaluate the local users on the system.

```powershell
$usersnow = Get-Content .\localusers.txt
$usersbaseline = Get-Content .\baseline\localusers.txt

Compare-Object $usersbaseline $usersnow
```

<figure><img src="/files/F4iesoYWaJ4j5gFAGiKS" alt=""><figcaption></figcaption></figure>

We can see the added username is dynamics.

We've used differential analysis to compare the system configuration to the baseline. Now, let's check for another way an attacker might maintain persistent access: a scheduled task.

### Scheduled Tasks Differential Analysis

Scheduled tasks are jobs that run on Windows at a specic time and with a specic frequency.

```powershell
Get-ScheduledTask
```

<figure><img src="/files/JpSJA9xW03E7VEuO3ByC" alt=""><figcaption></figcaption></figure>

```powershell
$scheduledtasksnow = Get-Content .\scheduledtasks.txt
$scheduledtasksbaseline = Get-Content .\baseline\scheduledtasks.txt

Compare-Object $scheduledtasksbaseline $scheduledtasksnow
```

<figure><img src="/files/WC562K9GWTVgGtVWZyXF" alt=""><figcaption></figcaption></figure>

Now we can see that the added scheduled task is **Microsoft eDynamics**.

### Scheduled Task Detail

So far we’ve found signs of malicious behavior, but let’s keep investigating the scheduled tasks. Use the `Export-ScheduledTask` command to examine them in detail.

```powershell
Export-ScheduledTask -TaskName "Microsoft eDynamics"
```

<figure><img src="/files/hvGrjbwlNE8A1rpsafwx" alt=""><figcaption></figcaption></figure>

Look at the closing element labeled Actions . Here we see that the scheduled task launches a command C:\WINDOWS\dynamics.exe , and it uses the sc.exe (Service Control) utility to start the service whenever this task is executed on the host.

### Removing Microsoft eDynamics

By analyzing the scheduled task, and through dierential analysis, we identied several components of this malicious software:

* A service named dynamics (dierential analysis).
* A process named dynamics (scheduled task detail).
* A program named C:\WINDOWS\dynamics.exe (scheduled task detail)
* A scheduled task named Microsoft eDynamics (dierential analysis).
* A local user account named dynamics (differential analysis)

Let's clean up the system, starting with the service.

```powershell
Stop-Service -Name Dynamics
```

<figure><img src="/files/e5ArrSUBsrKCDmk8sUml" alt=""><figcaption></figcaption></figure>

Next, stop the Dynamics process.

```powershell
Get-Process -Name Dynamics | Stop-Process
```

<figure><img src="/files/l1ccT8KFruPezja1kgiM" alt=""><figcaption></figcaption></figure>

Next, remove the dynamics.exe directory from the C:\Windows directory.

```powershell
Remove-Item C:\Windows\Dynamics.exe
```

<figure><img src="/files/0WYxCywcXxk0cQYivZNK" alt=""><figcaption></figcaption></figure>

The service has been stopped; now let’s remove it.

```powershell
sc.exe delete dynamics
#OR
Get-CimInstance -ClassName Win32_Service -Filter "Name='Dynamics'" | Remove-CimInstance
```

<figure><img src="/files/C9X2mmOztBJtyCBqiIwW" alt=""><figcaption></figcaption></figure>

Next, remove the scheduled task, using Unregister-ScheduledTask.

```powershell
Unregister-ScheduledTask -TaskName "Microsoft eDynamics"
```

<figure><img src="/files/cZfyMwDBMtaXq28IFClM" alt=""><figcaption></figcaption></figure>

Finally, remove the local user using Remove-LocalUser.

```powershell
Remove-LocalUser -Name dynamics
```

<figure><img src="/files/oPBvJ0yhfrsde0FySmNx" alt=""><figcaption></figcaption></figure>

## Bonus Challenge Walkthrough

1\) What TCP port is the backdoor listening on?

Now we've a baseline of the listening TCP ports.

```powershell
Get-NetTCPConnection -State Listen | Out-File tcpports-baseline.txt
```

Let's get the current listening TCP ports, save them to a file, load both files into variables, and compare to find differences.

<pre class="language-powershell"><code class="lang-powershell">Get-NetTCPConnection -State Listen | Out-File tcpports-cuurent.txt
<strong>$baseline = Get-Content .\tcpports-baseline.txt
</strong>$current = Get-Content .\tcpports-current.txt
Compare-Object $baseline $current
</code></pre>

<figure><img src="/files/IaLkLii74T2spSNYh3AQ" alt=""><figcaption></figcaption></figure>

The Compare-Object output shows a single line of difference. 1572 is the new listening TCP port.

Answer:  1027

2\) What is the process ID number of the backdoor?

We have the listening TCP port, but not the process ID. Let's use `Get-NetTCPConnection` to find it.

```powershell
Get-NetTCPConnection -State Listen | Where-Object -Property LocalPort 
-EQ 1027 | Select-Object -Property OwningProcess
```

<figure><img src="/files/scRTzJl40sW9ykseKuia" alt=""><figcaption></figcaption></figure>

Answer:  3248

3\) What is the parent process ID number of the backdoor?

```powershell
Get-CimInstance -ClassName Win32_Process | Where-Object -Property ProcessId -EQ 3248 | 
Select-Object -Property ParentProcessId
```

<figure><img src="/files/U6XePrmzllOPOLsIZdoQ" alt=""><figcaption></figcaption></figure>

Answer:  6544

4\) What is the flag shown when you connect to the backdoor?

```powershell
nc 127.0.0.1 1027
TheFlagisBack582474434
```

<figure><img src="/files/b8UGeJqeWuHmE4WA3Hje" alt=""><figcaption></figcaption></figure>

Answer:  TheFlagisBack582474434

5\) What TCP port is the backdoor listening on now?

The backdoor is listening on a different TCP port now. Since we know the process ID, we can get the tcp port number.

```powershell
Get-NetTCPConnection -State Listen | Where-Object -Property OwningProcess -EQ 3248 
| Select-Object LocalPort
```

<figure><img src="/files/Bnbv4IXxGgKxZ9d4vA2H" alt=""><figcaption></figcaption></figure>

Answer:  1029

6\) Stop the backdoor process using PowerShell.

```powershell
Get-Process -Id 6544
```

```powershell
Get-Process -Id 6544 | Stop-Process
```

<figure><img src="/files/APafScyhj3szk9iwUZZE" alt=""><figcaption></figcaption></figure>

7\) What is the process ID number of the backdoor?

We are asked to identify the process ID of a new backdoor. The clue here is that the new backdoor is a PowerShell-based process.

```powershell
Get-Process -Name powershell
```

<figure><img src="/files/armEUKgEWFVYzz8qNO8Y" alt=""><figcaption></figcaption></figure>

The output shows both the backdoor session and the analysis PowerShell session. To distinguish them, let's rerun the command and include a pipeline to get the process ID and start time.

```powershell
Get-Process -Name powershell | Select-Object Id, StartTime
```

<figure><img src="/files/HiLiZrCyIMlXJ9VVRer6" alt=""><figcaption></figcaption></figure>

The PowerShell process with the latest start time is the backdoor.

8\) What is the flag contained in the script executed by the backdoor?

```powershell
Get-CimInstance -Class Win32_Process | Where-Object -Property ProcessId -EQ 4316 | 
Select-Object -ExpandProperty CommandLine
```

<figure><img src="/files/6Ck1WF48lKzt1rwwZV1G" alt=""><figcaption></figcaption></figure>

Next we need to decode the Base64 value seen on the command line following `-enc`.

```powershell
[System.Text.Encoding]::Unicode.GetString([System.Convert]::FromBase64String
("dwBoAGkAbABlACgAJAB0AHIAdQBlACkAewAkAGYAbABhAGcAIAA9ACAAIgBTAGEAcwBxAHUAYQB0AGMAaAA4ADYAMwAyADQANwA5ADIAMAA2ACIAOwAgAFsAUwB5AHMAdABlAG0ALgBUAGgAcgBlAGEAZABpAG4AZwAuAFQAaAByAGUAYQBkAF0AOgA6AFMAbABlAGUAcAAoADEAMAAwADAAMAApAH0AOwA="))
```

<figure><img src="/files/ISpP3nZ0iYqrlfS3RN8v" alt=""><figcaption></figcaption></figure>

Answer:  Sasquatch8632479206

9\) We are finally asked to kill the backdoor process.

```powershell
PS C:\temp> Get-Process -Id 4316 | Stop-Process
```

<figure><img src="/files/RurFKIOYIlR7kbtydCFe" alt=""><figcaption></figcaption></figure>


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://faresbltagy.gitbook.io/footprintinglabs/sans-sec504-and-labs/book-one/live-examination.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
