# Part 5

## 🚨 **Remote Process Memory Injection via Rundll32**

***

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

#### 📝 **What is Remote Process Memory Injection via Rundll32?**

* **Remote Process Memory Injection** allows attackers to **inject malicious code into the memory of a legitimate process**.
* **Rundll32.exe**, a legitimate Windows binary, is often abused because:
  * It’s a **signed Microsoft binary**.
  * It can **execute DLLs and export functions** directly.
  * It is often **trusted by security tools**, reducing detection chances.

***

#### 📑 **Why Attackers Use Rundll32 for Memory Injection?**

* **Evasion:** Bypass antivirus and security tools by using a trusted binary.
* **Stealth:** Hide malicious activity within legitimate processes.
* **Execution Control:** Load malicious DLLs directly into memory.
* **Credential Theft:** Gain access to processes with higher privileges.

***

#### 📌 **How Rundll32 is Abused for Memory Injection**

| **Technique**                  | **Description**                        | **Command Example**                                                                        |
| ------------------------------ | -------------------------------------- | ------------------------------------------------------------------------------------------ |
| **Execute Malicious DLL**      | Run exported functions from a DLL.     | `rundll32.exe malicious.dll,ExportedFunction`                                              |
| **Reflective DLL Injection**   | Load a DLL directly into memory.       | `rundll32.exe javascript:"\..\mshtml,RunHTMLApplication";document.write("malicious code")` |
| **Inline Shellcode Execution** | Inject and execute shellcode directly. | `rundll32.exe advapi32.dll,CreateProcessAsUser`                                            |

***

#### 📌 **Common Tools for Rundll32 Injection**

| **Tool**           | **Purpose**                     |
| ------------------ | ------------------------------- |
| **Metasploit**     | Shellcode injection             |
| **Cobalt Strike**  | Reflective DLL injection        |
| **PowerSploit**    | Memory injection scripts        |
| **Process Hacker** | Process monitoring and analysis |

***

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

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

**🕵️ Check for Suspicious Rundll32 Processes**

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

**🕵️ Inspect Process Command Line Arguments**

```powershell
Get-WmiObject Win32_Process | Where-Object { $_.CommandLine -like "*rundll32*" } | Select-Object ProcessId, CommandLine
```

**🕵️ Look for Suspicious DLLs Loaded by Rundll32**

```powershell
Get-Process rundll32 -Module | Where-Object { $_.ModuleName -like "*.dll" }
```

**🕵️ Check Remote Thread Creation**

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

***

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

**🕵️ Detect Suspicious Rundll32 Execution**

```kusto
DeviceProcessEvents
| where FileName == "rundll32.exe"
| where ProcessCommandLine contains ".dll"
| where ProcessCommandLine contains "http" or ProcessCommandLine contains "reflective"
| project Timestamp, DeviceName, ProcessCommandLine, AccountName
```

**🕵️ Look for Remote Thread Creation in Rundll32**

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

**🕵️ Monitor for Reflective DLL Injection**

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

**🕵️ Identify Rundll32 Executing from Suspicious Paths**

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

**🕵️ Look for Remote Thread Activity in Memory**

```kusto
DeviceProcessEvents
| where ProcessCommandLine contains "VirtualAlloc"
| where ProcessCommandLine contains "WriteProcessMemory"
| 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 process exits).                |
| **4656**     | Handle to an object was requested (memory access).        |
| **4663**     | An attempt was made to access an object (e.g., DLL file). |
| **7045**     | A service was installed in the system.                    |

**📌 Focus on Event ID 4688:**

* Look for:

  ```powershell
  ProcessName: rundll32.exe
  CommandLine: rundll32.exe C:\Temp\malicious.dll,Start
  ```

**📌 Focus on Event ID 4656:**

* Look for attempts to access suspicious memory regions.

**📌 Focus on Event ID 7045:**

* Look for newly installed services linked to `rundll32.exe`.

***

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

#### 1️⃣ **Trace Rundll32 Command History**

* Review command lines for suspicious patterns:

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

***

#### 2️⃣ **Inspect Loaded DLLs**

* Identify suspicious DLLs linked to `rundll32.exe`:

```powershell
Get-Process -Name rundll32 -Module | Where-Object { $_.ModuleName -like "*.dll" }
```

***

#### 3️⃣ **Analyze Remote Threads**

* Look for remote threads within legitimate processes:

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

***

#### 4️⃣ **Memory Dump Analysis**

* Dump `rundll32` process memory for further inspection:

```powershell
procdump.exe -ma <ProcessID> rundll32_dump.dmp
```

***

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

#### 📌 **1. Terminate Suspicious Rundll32 Processes**

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

#### 📌 **2. Remove Malicious DLLs**

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

#### 📌 **3. Quarantine Suspicious Files**

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

#### 📌 **4. Block Rundll32 Execution in Specific Folders**

```powershell
New-AppLockerPolicy -RuleType Deny -Path "C:\Temp\rundll32.exe"
```

#### 📌 **5. Enable Advanced Threat Protection (ATP) Policies**

* Enable behavior-based detection and blocking.

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

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

***

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

1. **Monitor Rundll32 Execution:**
   * Block execution of `rundll32.exe` from `Temp` and `AppData`.
2. **Enable Script Block Logging:**
   * Capture PowerShell commands with `rundll32`.
3. **Use Windows Defender ATP:**
   * Enable behavior monitoring and memory scanning.
4. **Implement Application Whitelisting:**
   * Use **AppLocker** or **Windows Defender Application Control (WDAC)**.
5. **Restrict DLL Execution in Temp Folders:**
   * Prevent execution of DLLs from user-writable directories.
6. **Monitor Process Relationships:**
   * Regularly check parent-child process trees.

***

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

* **Rundll32 is a Trusted Binary:** Attackers abuse it for stealth.
* **Monitor Command Lines:** Look for `rundll32` with DLL paths in `Temp` or `AppData`.
* **Focus on Event IDs:** **4688, 4656, 4663, 7045**.
* **Use Threat Intelligence:** Leverage tools like **VirusTotal** for DLL analysis.
* **Implement Application Control:** Block unauthorized DLL executions.

***

## **Non-Baselined LNK Target Command:**

***

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

#### 📝 **What is a Non-Baselined LNK Target Command?**

* **LNK files** are **Windows shortcut files** with a `.lnk` extension. They are used to **point to an executable file or a command**.
* Attackers can modify the **"Target" field** in LNK files to:
  * **Execute malicious scripts or binaries.**
  * **Bypass security tools by using trusted processes.**
  * **Maintain persistence through startup folders.**

#### 📑 **Why Attackers Use LNK Files?**

* **Stealth:** LNK files often bypass security detections.
* **Trusted Binary Execution:** LNK files can invoke `cmd.exe`, `powershell.exe`, or `rundll32.exe`.
* **Persistence:** Placed in **Startup folders** for automatic execution.
* **Social Engineering:** Disguised as legitimate shortcuts (e.g., `Document.lnk`).

***

#### 📌 **Common Techniques for LNK Target Abuse**

| **Technique**                  | **Description**                               | **Example Command**                                                                          |
| ------------------------------ | --------------------------------------------- | -------------------------------------------------------------------------------------------- |
| **Malicious Target Path**      | Execute malware via an LNK file.              | `cmd.exe /c malicious.exe`                                                                   |
| **PowerShell Execution**       | Run a malicious PowerShell script.            | `powershell.exe -NoProfile -ExecutionPolicy Bypass -File payload.ps1`                        |
| **DLL Hijacking**              | Run malicious DLLs via legitimate programs.   | `rundll32.exe malicious.dll,ExportedFunction`                                                |
| **Environment Variable Abuse** | Use environment variables to obfuscate paths. | `%APPDATA%\malicious.exe`                                                                    |
| **LNK in Startup Folder**      | Auto-execute LNK at boot.                     | `C:\Users\<User>\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup\shortcut.lnk` |

***

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

1. **Startup Folder Persistence:** Place LNK file in `Startup` to run on boot.
2. **Fake Document Shortcut:** `Invoice.lnk` executes `powershell.exe -EncodedCommand`.
3. **Hidden Target Commands:** LNK references commands that run from `%TEMP%`.
4. **Abuse of Trusted Binaries:** Use `cmd.exe`, `powershell.exe`, or `mshta.exe` via LNK Target.

***

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

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

**🕵️ List LNK Files with Non-Standard Targets**

```powershell
Get-ChildItem -Path "C:\" -Recurse -Filter "*.lnk" | ForEach-Object {
    $target = (New-Object -ComObject WScript.Shell).CreateShortcut($_.FullName).TargetPath
    if ($target -match "cmd.exe|powershell.exe|rundll32.exe") {
        Write-Output "$($_.FullName) -> $target"
    }
}
```

**🕵️ Check Startup Folder for Suspicious LNK Files**

```powershell
Get-ChildItem -Path "C:\Users\*\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup" -Filter "*.lnk"
```

**🕵️ Inspect LNK Metadata for Suspicious Targets**

```powershell
Get-ChildItem -Path "C:\" -Filter "*.lnk" -Recurse | Select-Object Name, FullName, LastWriteTime
```

**🕵️ Identify Recent LNK File Modifications**

```powershell
Get-ChildItem -Path "C:\" -Recurse -Filter "*.lnk" | Where-Object { $_.LastWriteTime -gt (Get-Date).AddDays(-7) }
```

***

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

**🕵️ Detect Suspicious LNK File Execution**

```kusto
DeviceProcessEvents
| where FileName endswith ".lnk"
| where ProcessCommandLine contains "cmd.exe" or ProcessCommandLine contains "powershell.exe"
| project Timestamp, DeviceName, ProcessCommandLine, AccountName
```

**🕵️ Identify LNK Files with Malicious Targets**

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

**🕵️ Monitor PowerShell or CMD Executed via LNK**

```kusto
DeviceProcessEvents
| where InitiatingProcessFileName endswith ".lnk"
| where ProcessCommandLine contains "powershell.exe" or ProcessCommandLine contains "cmd.exe"
| project Timestamp, DeviceName, ProcessCommandLine, InitiatingProcessFileName, AccountName
```

**🕵️ Detect LNK in Startup Folder**

```kusto
DeviceFileEvents
| where FolderPath contains "Startup"
| where FileName endswith ".lnk"
| project Timestamp, DeviceName, FileName, FolderPath, AccountName
```

**🕵️ Trace Suspicious File Executions from LNK Files**

```kusto
DeviceProcessEvents
| where InitiatingProcessFileName endswith ".lnk"
| where ProcessCommandLine contains ".dll"
| project Timestamp, DeviceName, ProcessCommandLine, AccountName
```

***

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

| **Event ID** | **Description**                                                |
| ------------ | -------------------------------------------------------------- |
| **4688**     | A new process was created (LNK Target Execution).              |
| **4663**     | Object access attempt (LNK file access).                       |
| **4656**     | Handle to an object was requested (e.g., LNK metadata access). |
| **7045**     | A service was installed (LNK-based persistence via services).  |

**📌 Focus on Event ID 4688:**

* Look for:

  ```makefile
  ProcessName: powershell.exe, cmd.exe, rundll32.exe
  CommandLine: *.lnk
  ```

**📌 Focus on Event ID 4663:**

* Track LNK file access activity.

***

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

#### 1️⃣ **Inspect LNK File Metadata**

* Review target paths:

```powershell
$lnk = (New-Object -ComObject WScript.Shell).CreateShortcut("C:\Path\to\file.lnk")
$lnk.TargetPath
$lnk.Arguments
```

***

#### 2️⃣ **Trace Process Relationships**

* Check process lineage for LNK abuse:

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

***

#### 3️⃣ **Examine LNK File Creation History**

* Check recently modified LNK files:

```powershell
Get-ChildItem -Path "C:\" -Recurse -Filter "*.lnk" | Where-Object { $_.LastWriteTime -gt (Get-Date).AddDays(-7) }
```

***

#### 4️⃣ **Check Startup Folder**

* Review LNK files in startup paths:

```powershell
Get-ChildItem -Path "C:\Users\*\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup"
```

***

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

#### 📌 **1. Remove Suspicious LNK Files**

```powershell
Remove-Item -Path "C:\Path\to\suspicious.lnk" -Force
```

#### 📌 **2. Disable Executables from Non-Standard Paths**

```powershell
New-AppLockerPolicy -RuleType Deny -Path "C:\Temp\*.exe"
```

#### 📌 **3. Terminate Malicious Processes**

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

#### 📌 **4. Reset User Accounts**

```powershell
net user <User> NewP@ssw0rd!
```

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

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

***

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

1. **Enable Script and Command Line Logging:**
   * Capture suspicious LNK executions.
2. **Monitor Startup Folders:**
   * Regularly inspect `Startup` directories.
3. **Restrict LNK File Creation:**
   * Block LNK file creation in sensitive directories.
4. **Implement AppLocker Policies:**
   * Block execution of suspicious processes from LNK files.
5. **Educate End-Users:**
   * Train users to recognize suspicious LNK files.

***

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

* **LNK Files Are Powerful Attack Vectors:** Often used for stealthy execution.
* **Focus on Startup and Temp Folders:** Common storage for malicious LNK files.
* **Monitor Event IDs:** **4688**, **4663**, **4656**, **7045**.
* **Use Threat Intelligence:** Validate suspicious file hashes with **VirusTotal**.
* **Restrict Unauthorized LNK File Usage:** Use AppLocker and WDAC.

***

## 🚨 **Collecting UUID from a Device**

***

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

#### 📝 **What is UUID Collection?**

* **UUID (Universally Unique Identifier)** is a unique identifier used by operating systems to **identify devices, installations, or user profiles.**
* Attackers often collect UUIDs to:
  * **Fingerprint Devices:** Track or uniquely identify a system.
  * **Bypass Security Controls:** UUIDs may be used in **whitelisting mechanisms**.
  * **Enhance Persistence:** Map UUIDs to compromised devices for long-term access.
  * **Evasion:** UUIDs may assist in developing more tailored attacks.

***

#### 📑 **Why Do Attackers Collect UUIDs?**

* **Targeted Attacks:** Build campaigns targeting specific devices.
* **Anti-Forensics:** Avoid detection by profiling devices.
* **Authentication Abuse:** UUIDs can sometimes be part of system authentication mechanisms.
* **System Persistence:** Link malicious software or implants to specific UUIDs.

***

#### 📌 **Common Methods to Retrieve UUIDs**

| **Method**                      | **Description**                      | **Command Example**                                            |
| ------------------------------- | ------------------------------------ | -------------------------------------------------------------- |
| **SystemInfo Command**          | Display hardware and UUID details.   | \`systeminfo                                                   |
| **WMIC Query**                  | Query hardware UUID via WMI.         | `wmic csproduct get UUID`                                      |
| **PowerShell Query**            | Retrieve UUID via PowerShell.        | \`Get-CimInstance -Class Win32\_ComputerSystemProduct          |
| **Registry Query**              | UUIDs may exist in Windows Registry. | `reg query HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Cryptography` |
| **Direct Hardware Interaction** | Access BIOS/UEFI UUID directly.      | `dmidecode -s system-uuid` (Linux)                             |

***

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

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

**🕵️ Identify UUID Queries via WMIC**

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

**🕵️ Search for UUID Retrieval Commands in PowerShell**

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

**🕵️ Monitor Registry Access for Cryptography Keys**

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

**🕵️ Track Command-Line UUID Queries**

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

***

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

**🕵️ Detect UUID Collection via WMIC**

```kusto
DeviceProcessEvents
| where ProcessCommandLine contains "wmic"
| where ProcessCommandLine contains "UUID"
| project Timestamp, DeviceName, ProcessCommandLine, AccountName
```

**🕵️ Monitor UUID Retrieval via PowerShell**

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

**🕵️ Identify Registry Access to Cryptography Keys**

```kusto
DeviceRegistryEvents
| where RegistryKey contains "SOFTWARE\\Microsoft\\Cryptography"
| where ActionType == "RegistryValueRead"
| project Timestamp, DeviceName, RegistryKey, AccountName
```

**🕵️ Trace UUID Retrieval via Command Line Tools**

```kusto
DeviceProcessEvents
| where FileName contains "systeminfo"
| where ProcessCommandLine contains "UUID"
| project Timestamp, DeviceName, ProcessCommandLine, AccountName
```

**🕵️ Detect Suspicious Script Execution for UUID Collection**

```kusto
DeviceScriptEvents
| where ScriptContent contains "UUID"
| project Timestamp, DeviceName, ScriptContent, AccountName
```

***

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

| **Event ID** | **Description**                                                          |
| ------------ | ------------------------------------------------------------------------ |
| **4688**     | A new process was created (e.g., `wmic UUID`).                           |
| **4663**     | An attempt was made to access an object (Registry Key for Cryptography). |
| **4104**     | PowerShell script block execution (UUID retrieval).                      |
| **4624**     | Successful account logon (Tracking accounts used for UUID retrieval).    |

**📌 Focus on Event ID 4688:**

* Look for:

  ```powershell
  ProcessCommandLine: wmic csproduct get UUID
  ProcessCommandLine: Get-CimInstance -Class Win32_ComputerSystemProduct
  ```

**📌 Focus on Event ID 4663:**

* Monitor registry access:

```
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Cryptography
```

**📌 Focus on Event ID 4104:**

* Look for PowerShell UUID retrieval scripts:

  ```vbnet
  Get-CimInstance -Class Win32_ComputerSystemProduct | Select-Object UUID
  ```

***

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

#### 1️⃣ **Trace Commands Used for UUID Retrieval**

* Look for recent UUID queries:

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

***

#### 2️⃣ **Inspect Registry Access**

* Check if attackers accessed cryptography keys:

```powershell
reg query HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Cryptography
```

***

#### 3️⃣ **Trace PowerShell Activity**

* Review executed PowerShell commands:

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

***

#### 4️⃣ **Inspect Scripts on the Device**

* Search for UUID keywords in scripts:

```powershell
Select-String -Path "C:\Scripts\*.ps1" -Pattern "UUID"
```

***

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

#### 📌 **1. Terminate Suspicious Processes**

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

#### 📌 **2. Block Unauthorized WMI Queries**

* Restrict WMI access for non-admin accounts.

#### 📌 **3. Audit and Reset Compromised Accounts**

* Force password reset:

```powershell
net user User NewP@ssw0rd!
```

#### 📌 **4. Quarantine Suspicious Scripts**

```powershell
Move-Item -Path "C:\Scripts\suspicious.ps1" -Destination "C:\Quarantine"
```

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

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

***

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

1. **Restrict WMI Access:**
   * Only allow trusted accounts to run `wmic` commands.
2. **Enable Script Block Logging:**
   * Capture all PowerShell command activity.
3. **Audit Cryptography Registry Access:**
   * Monitor `HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Cryptography`.
4. **Apply Least Privilege Principle:**
   * Limit admin access to UUID-related queries.
5. **Enable Advanced Threat Protection (ATP):**
   * Activate behavioral analytics for WMI and PowerShell activity.
6. **Monitor Event IDs:**
   * **4688, 4663, 4104.**

***

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

* **UUIDs Are Valuable Targets:** They aid in device fingerprinting and persistent access.
* **Monitor Command-Line Tools:** Focus on `wmic`, `systeminfo`, and PowerShell UUID queries.
* **Watch Registry Activity:** Pay close attention to the `Cryptography` registry key.
* **Use Threat Intelligence Tools:** Validate findings with tools like **VirusTotal**.
* **Enable Script and Command Logging:** Catch malicious scripts early.

***

## 🚨 **Detect Suspicious WerFault Child Process**

***

### 🔍 **1. Attack Breakown**

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

* **WerFault.exe** is the **Windows Error Reporting (WER) service executable**, responsible for handling application crash reports and collecting debugging information.
* Attackers often abuse **WerFault.exe** because:
  * It is a **trusted Windows binary** (living-off-the-land binary - LoLBins).
  * It can be used to **execute arbitrary payloads** as a child process.
  * It can bypass antivirus and security monitoring tools.

***

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

* **Stealth:** Bypass detection by masquerading malicious payloads as legitimate error reports.
* **Execution Control:** Run code without leaving obvious traces.
* **Privilege Escalation:** Gain higher-level privileges by running under system context.
* **Persistence:** Maintain access using scheduled crashes or WER hijacking.

***

#### 📌 **Common WerFault Attack Techniques**

| **Technique**                       | **Description**                                   | **Example Command**                                                                                     |
| ----------------------------------- | ------------------------------------------------- | ------------------------------------------------------------------------------------------------------- |
| **Child Process Injection**         | Create malicious child processes under WerFault.  | `WerFault.exe -u -p <PID> -s <SubProcessID>`                                                            |
| **Reflective DLL Injection**        | Load malicious DLLs into WerFault memory.         | `WerFault.exe C:\malware.dll`                                                                           |
| **Payload Execution**               | Direct execution of malicious payloads.           | `WerFault.exe /c C:\Temp\payload.exe`                                                                   |
| **Hijacking Error Reporting Paths** | Modify registry keys to redirect WER crash paths. | `reg add "HKLM\Software\Microsoft\Windows NT\CurrentVersion\Image File Execution Options\WerFault.exe"` |

***

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

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

**🕵️ Identify WerFault Processes with Suspicious Command Lines**

```powershell
Get-WmiObject Win32_Process | Where-Object { $_.Name -eq "WerFault.exe" -and $_.CommandLine -like "*-p*" } | Select-Object ProcessId, ParentProcessId, CommandLine
```

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

```powershell
Get-CimInstance Win32_Process | Where-Object { $_.ParentProcessId -eq <PID> } | Select-Object ProcessId, Name, CommandLine
```

**🕵️ Trace DLLs Loaded by WerFault**

```powershell
Get-Process -Name WerFault -Module | Where-Object { $_.ModuleName -like "*.dll" }
```

**🕵️ List Suspicious Child Processes of WerFault**

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

***

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

**🕵️ Detect Suspicious WerFault Process Execution**

```kusto
DeviceProcessEvents
| where FileName == "WerFault.exe"
| where ProcessCommandLine contains "-p" or ProcessCommandLine contains "-u"
| project Timestamp, DeviceName, ProcessCommandLine, ParentProcessName, AccountName
```

**🕵️ Look for WerFault as a Parent Process**

```kusto
DeviceProcessEvents
| where ParentProcessFileName == "WerFault.exe"
| project Timestamp, DeviceName, ProcessCommandLine, FileName, AccountName
```

**🕵️ Detect Suspicious DLL Loaded by WerFault**

```kusto
DeviceImageLoadEvents
| where InitiatingProcessFileName == "WerFault.exe"
| where FileName endswith ".dll"
| where FileName contains "Temp"
| project Timestamp, DeviceName, FileName, FolderPath, AccountName
```

**🕵️ Identify Remote Thread Activity in WerFault**

```kusto
DeviceProcessEvents
| where FileName == "WerFault.exe"
| where ProcessCommandLine contains "VirtualAlloc"
| where ProcessCommandLine contains "WriteProcessMemory"
| project Timestamp, DeviceName, ProcessCommandLine, AccountName
```

**🕵️ Detect Suspicious Registry Modification for WER**

```kusto
DeviceRegistryEvents
| where RegistryKey contains "Image File Execution Options\\WerFault.exe"
| where ActionType == "RegistryValueSet"
| project Timestamp, DeviceName, RegistryKey, RegistryValueName, AccountName
```

***

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

| **Event ID** | **Description**                                       |
| ------------ | ----------------------------------------------------- |
| **4688**     | A new process was created (e.g., `WerFault.exe`).     |
| **4689**     | Process termination (trace exits).                    |
| **4663**     | Object access attempt (e.g., DLL or registry access). |
| **7045**     | A service was installed in the system.                |

**📌 Focus on Event ID 4688:**

* Look for:

  ```powershell
  ProcessName: WerFault.exe
  CommandLine: WerFault.exe -u -p <PID> -s <SubProcessID>
  ```

**📌 Focus on Event ID 4663:**

* Check DLL paths:

  ```makefile
  ObjectName: C:\Temp\malicious.dll
  ```

***

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

#### 1️⃣ **Trace WerFault Child Processes**

* Identify suspicious child processes:

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

***

#### 2️⃣ **Inspect Loaded DLLs**

* List all DLLs loaded by WerFault:

```powershell
Get-Process -Name WerFault -Module
```

***

#### 3️⃣ **Check WerFault Registry Hijacking**

* Look for WER registry hijacking:

```powershell
reg query "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options\WerFault.exe"
```

***

#### 4️⃣ **Review Process Command Lines**

* Analyze command lines for suspicious arguments:

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

***

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

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

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

#### 📌 **2. Remove Malicious DLLs**

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

#### 📌 **3. Restore WER Registry Values**

* Reset registry settings:

```powershell
reg delete "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options\WerFault.exe" /f
```

#### 📌 **4. Block Execution from Suspicious Paths**

```powershell
New-AppLockerPolicy -RuleType Deny -Path "C:\Temp\*.dll"
```

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

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

***

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

1. **Monitor WerFault Execution:**
   * Track Event IDs **4688**, **4663**, **7045**.
2. **Enable Command Line Auditing:**
   * Capture suspicious arguments in process creation events.
3. **Restrict WerFault in Non-Standard Paths:**
   * Block execution from user-writable directories.
4. **Implement Application Control Policies:**
   * Use **AppLocker** or **Windows Defender Application Control (WDAC)**.
5. **Patch and Update Systems:**
   * Apply latest Windows updates to prevent known exploits.
6. **Educate Security Teams:**
   * Raise awareness about **WerFault abuse** techniques.

***

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

* **WerFault.exe is Often Abused:** Trusted by Windows, it's an ideal target for attackers.
* **Focus on Child Processes:** Analyze processes spawned by `WerFault.exe`.
* **Monitor DLL Loads:** Pay attention to `.dll` files loaded from non-standard paths.
* **Watch for Registry Hijacking:** Registry paths under `Image File Execution Options`.
* **Use Behavioral Analytics:** Monitor arguments in `WerFault.exe` executions.

***

## 🚨 **Abnormal File Extension in Public User Directory**

***

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

#### 📝 **What is an Abnormal File Extension in Public User Directory?**

* The **Public User Directory** (`C:\Users\Public`) is accessible to all users and is commonly used for **sharing files between users and processes** on the same system.
* Attackers often abuse this directory to:
  * **Store malicious payloads** with abnormal or uncommon file extensions.
  * **Maintain persistence** by placing executables or scripts in this directory.
  * **Avoid detection**, as the directory is often overlooked by monitoring tools.

#### 📑 **Why Attackers Use Public Directories?**

* **Accessibility:** Accessible to all users and processes by default.
* **Persistence:** Files placed here may not be immediately flagged.
* **Evasion:** Easier to bypass detection tools monitoring user-specific directories.
* **Shared Access:** Facilitates multi-user access without elevated privileges.

***

#### 📌 **Common Abnormal File Extensions Used by Attackers**

| **Extension** | **Purpose**                     | **Example File Name** |
| ------------- | ------------------------------- | --------------------- |
| **.exe**      | Malicious executables           | `update.exe`          |
| **.dll**      | Dynamic libraries for injection | `malicious.dll`       |
| **.bat**      | Batch scripts                   | `run.bat`             |
| **.cmd**      | Command-line scripts            | `payload.cmd`         |
| **.ps1**      | PowerShell scripts              | `script.ps1`          |
| **.js**       | JavaScript scripts              | `loader.js`           |
| **.vbs**      | VBScript files                  | `install.vbs`         |
| **.dat**      | Encrypted payloads              | `config.dat`          |
| **.tmp**      | Temporary executable files      | `tempfile.tmp`        |

***

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

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

**🕵️ List Suspicious File Extensions in Public Directory**

```powershell
Get-ChildItem -Path "C:\Users\Public" -Recurse | Where-Object {
    $_.Extension -in @(".exe", ".dll", ".bat", ".cmd", ".ps1", ".js", ".vbs", ".dat", ".tmp")
} | Select-Object FullName, Extension, LastWriteTime
```

**🕵️ Check Recently Created/Modified Files**

```powershell
Get-ChildItem -Path "C:\Users\Public" -Recurse | Where-Object {
    $_.LastWriteTime -gt (Get-Date).AddDays(-7)
} | Select-Object FullName, LastWriteTime
```

**🕵️ Inspect File Owners in Public Directory**

```powershell
Get-ChildItem -Path "C:\Users\Public" -Recurse | Select-Object FullName, @{Name="Owner";Expression={(Get-Acl $_.FullName).Owner}}
```

**🕵️ Find Executable Files in Public Directory**

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

***

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

**🕵️ Detect Abnormal File Extensions in Public Directory**

```kusto
DeviceFileEvents
| where FolderPath contains "C:\\Users\\Public"
| where FileName endswith ".exe" or FileName endswith ".bat" or FileName endswith ".ps1" or FileName endswith ".js" or FileName endswith ".dll"
| project Timestamp, DeviceName, FileName, FolderPath, AccountName, ActionType
```

**🕵️ Identify Recent File Creations in Public Directory**

```kusto
DeviceFileEvents
| where FolderPath contains "C:\\Users\\Public"
| where ActionType == "FileCreated"
| where Timestamp > ago(7d)
| project Timestamp, DeviceName, FileName, FolderPath, AccountName
```

**🕵️ Monitor Suspicious Processes Triggered from Public Directory**

```kusto
DeviceProcessEvents
| where FolderPath contains "C:\\Users\\Public"
| where FileName endswith ".exe" or FileName endswith ".bat" or FileName endswith ".ps1"
| project Timestamp, DeviceName, ProcessCommandLine, AccountName
```

**🕵️ Check PowerShell and CMD Files in Public Directory**

```kusto
DeviceFileEvents
| where FolderPath contains "C:\\Users\\Public"
| where FileName endswith ".ps1" or FileName endswith ".cmd"
| project Timestamp, DeviceName, FileName, FolderPath, AccountName
```

**🕵️ Look for DLL Files Loaded from Public Directory**

```kusto
DeviceImageLoadEvents
| where FolderPath contains "C:\\Users\\Public"
| where FileName endswith ".dll"
| project Timestamp, DeviceName, FileName, FolderPath, AccountName
```

***

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

| **Event ID** | **Description**                                                       |
| ------------ | --------------------------------------------------------------------- |
| **4688**     | A new process was created (e.g., `cmd.exe`, `powershell.exe`).        |
| **4663**     | An object access attempt was detected (e.g., file access).            |
| **4656**     | Handle to an object was requested (e.g., file handle).                |
| **7045**     | A service was installed on the system (e.g., via public executables). |

**📌 Focus on Event ID 4688:**

* Look for:

  ```powershell
  ProcessCommandLine: C:\Users\Public\*.exe
  ProcessCommandLine: C:\Users\Public\*.bat
  ```

**📌 Focus on Event ID 4663:**

* Look for file modifications:

  ```powershell
  ObjectName: C:\Users\Public\*.ps1
  ```

***

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

#### 1️⃣ **Inspect Suspicious Files in Public Directory**

* Check file details:

```powershell
Get-ItemProperty -Path "C:\Users\Public\malicious.exe"
```

***

#### 2️⃣ **Trace Process Tree from Suspicious Files**

* Identify parent-child relationships:

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

***

#### 3️⃣ **Inspect File Hashes**

* Generate hashes and compare on VirusTotal:

```powershell
Get-FileHash -Path "C:\Users\Public\malicious.exe" -Algorithm SHA256
```

***

#### 4️⃣ **Review Recent Events in Public Directory**

* Check event logs for file modifications:

```powershell
Get-WinEvent -FilterHashtable @{LogName='Security'; Id=4663} | Where-Object { $_.Message -like "*C:\Users\Public*" }
```

***

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

#### 📌 **1. Quarantine Suspicious Files**

```powershell
Move-Item -Path "C:\Users\Public\malicious.exe" -Destination "C:\Quarantine"
```

#### 📌 **2. Terminate Malicious Processes**

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

#### 📌 **3. Restrict Public Directory Permissions**

```powershell
icacls "C:\Users\Public" /inheritance:r
```

#### 📌 **4. Block Executables in Public Directory**

* Create AppLocker rule:

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

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

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

***

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

1. **Enable File Auditing:**
   * Enable auditing for `C:\Users\Public`.
2. **Restrict Write Permissions:**
   * Limit write access to trusted users.
3. **Monitor File Extensions:**
   * Alert on `.exe`, `.dll`, `.ps1`, `.bat` in public directories.
4. **Enable AppLocker or WDAC:**
   * Block execution of files in `C:\Users\Public`.
5. **Patch and Update:**
   * Keep systems and security tools up to date.
6. **Educate Users:**
   * Train users to avoid executing files from public directories.

***

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

* **Monitor Public Directories Closely:** They are common targets for malware storage.
* **Focus on Event IDs:** **4688**, **4663**, **4656**, **7045**.
* **Restrict Permissions:** Prevent unauthorized writes to public folders.
* **Regular Scanning:** Ensure frequent scans of public directories.

***


---

# 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-5.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.
