# Part 4

## 🚨 **Exploitation of Remote Services**

***

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

#### 📝 **What is Exploitation of Remote Services?**

* **Exploitation of Remote Services** occurs when attackers **abuse vulnerabilities in remote services** (e.g., RDP, SMB, SSH, FTP) to gain unauthorized access to systems.
* Common remote services targeted include:
  * **Remote Desktop Protocol (RDP)**
  * **Server Message Block (SMB)**
  * **Secure Shell (SSH)**
  * **Telnet**
  * **FTP**

#### 📑 **Why Attackers Exploit Remote Services?**

* **Initial Access:** Gain foothold on a target system.
* **Privilege Escalation:** Exploit misconfigurations or weak credentials.
* **Persistence:** Maintain long-term access.
* **Lateral Movement:** Move across systems within the network.
* **Data Exfiltration:** Steal sensitive information.

#### 📌 **Common Exploited Services and Techniques**

| **Service** | **Common Exploitation Techniques**                             | **Example Tools**        |
| ----------- | -------------------------------------------------------------- | ------------------------ |
| **RDP**     | Brute Force, Credential Stuffing, RDP BlueKeep (CVE-2019-0708) | `xfreerdp`, `Hydra`      |
| **SMB**     | EternalBlue (CVE-2017-0144), SMBGhost (CVE-2020-0796)          | `Metasploit`, `Impacket` |
| **SSH**     | Credential Stuffing, Weak Key Exploitation                     | `Hydra`, `CrackMapExec`  |
| **FTP**     | Anonymous Login Exploitation, Directory Traversal              | `Nmap`, `Hydra`          |
| **Telnet**  | Default Credential Exploitation                                | `Hydra`, `Metasploit`    |

***

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

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

**🕵️ Check Active Remote Sessions**

```powershell
qwinsta
```

**🕵️ Review RDP Connection Logs**

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

**🕵️ Check for Suspicious SMB Connections**

```powershell
Get-SmbSession | Select-Object ClientComputerName, UserName, SessionId
```

**🕵️ Review Active SSH Connections**

```powershell
netstat -ano | findstr ":22"
```

**🕵️ Identify Failed Login Attempts**

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

***

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

**🕵️ Detect Suspicious Remote Login Attempts**

```kusto
SecurityEvent
| where EventID == 4625
| where AccountName != "defaultaccount"
| summarize FailedAttempts = count() by AccountName, IpAddress
| where FailedAttempts > 5
```

**🕵️ Identify SMB Exploitation Attempts**

```kusto
DeviceNetworkEvents
| where RemotePort == 445
| where ActionType == "ConnectionFailed"
| summarize count() by RemoteIP
| where count_ > 10
```

**🕵️ Monitor RDP Brute Force Attempts**

```kusto
SecurityEvent
| where EventID == 4625
| where LogonType == 10 or LogonType == 7
| summarize FailedAttempts = count() by IpAddress, AccountName
| where FailedAttempts > 5
```

**🕵️ Detect EternalBlue Exploitation Patterns**

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

**🕵️ SSH Access Attempts**

```kusto
DeviceNetworkEvents
| where RemotePort == 22
| where ActionType == "ConnectionSuccess"
| summarize ConnectionCount = count() by RemoteIP, AccountName
| where ConnectionCount > 5
```

**🕵️ Monitor FTP Connections**

```kusto
DeviceNetworkEvents
| where RemotePort == 21
| where ActionType == "ConnectionSuccess"
| summarize ConnectionCount = count() by RemoteIP, AccountName
```

***

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

| **Event ID** | **Description**                                   |
| ------------ | ------------------------------------------------- |
| **4624**     | Successful logon.                                 |
| **4625**     | Failed logon attempt.                             |
| **4776**     | The computer attempted to validate credentials.   |
| **4648**     | A logon was attempted using explicit credentials. |
| **4672**     | Special privileges assigned to new logon.         |

**📌 Focus on Event ID 4625:**

* Repeated login failures from a single **IP address**.

**📌 Focus on Event ID 4672:**

* Look for **privileged account logins** from suspicious IPs.

***

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

#### 1️⃣ **Trace Failed Authentication Attempts**

* Analyze failed authentication patterns:

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

***

#### 2️⃣ **Identify Active Remote Sessions**

* List active RDP sessions:

```powershell
qwinsta
```

* Check SMB Sessions:

```powershell
Get-SmbSession
```

***

#### 3️⃣ **Inspect Process Activity Related to Remote Services**

* Look for suspicious processes:

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

***

#### 4️⃣ **Check Open Ports**

* Verify open ports for remote services:

```powershell
netstat -ano | findstr ":3389 :445 :22"
```

***

#### 5️⃣ **Review Suspicious Network Connections**

* Identify remote connections:

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

***

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

#### 📌 **1. Terminate Unauthorized Sessions**

```powershell
logoff <SessionID>
```

#### 📌 **2. Disable Unused Remote Services**

```powershell
Set-Service -Name TermService -StartupType Disabled
```

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

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

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

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

#### 📌 **5. Patch Known Vulnerabilities**

* Apply patches for vulnerabilities like **BlueKeep (CVE-2019-0708)** and **EternalBlue (CVE-2017-0144)**.

#### 📌 **6. Enable Network Level Authentication (NLA) for RDP**

```powershell
reg add "HKLM\System\CurrentControlSet\Control\Terminal Server\WinStations\RDP-Tcp" /v UserAuthentication /t REG_DWORD /d 1 /f
```

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

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

***

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

1. **Disable Unused Remote Services:**
   * Turn off RDP, SMB, FTP, and Telnet if not needed.
2. **Implement Multi-Factor Authentication (MFA):**
   * Add MFA to remote access.
3. **Apply Network Segmentation:**
   * Isolate systems with sensitive remote services.
4. **Use Strong Password Policies:**
   * Enforce complex passwords.
5. **Patch Systems Regularly:**
   * Keep systems updated to prevent exploitation.
6. **Enable Account Lockout Policies:**

```powershell
powershellنسخ الكودnet accounts /lockoutthreshold:5
```

7. **Monitor Service Logs:**
   * Regularly review **Event IDs 4625, 4672, 4648**.

***

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

* **Remote Services Are Prime Targets:** Monitor RDP, SMB, SSH, and FTP.
* **Patch Known Vulnerabilities:** Keep services updated.
* **Implement Logging and Auditing:** Enable **Event IDs 4625, 4672**.
* **Use Network Segmentation:** Restrict access to critical services.
* **Apply Least Privilege Principle:** Limit admin access on remote services.

***

## 🚨 **File and Directory Discovery: Advanced Threat Analysis**

***

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

#### 📝 **What is File and Directory Discovery?**

* **File and Directory Discovery** involves **identifying sensitive files, folders, and directories** on a compromised system.
* Attackers use discovery techniques to:
  * Locate **sensitive data** (e.g., credentials, configuration files).
  * Identify **critical system directories** for further attacks.
  * Determine **backup locations** and **log files**.
  * Plan **data exfiltration paths**.

***

#### 📑 **Why Attackers Use File and Directory Discovery?**

* **Gather Information:** Locate files with sensitive data (e.g., `.env`, `config.xml`, `password.txt`).
* **Privilege Escalation:** Identify configuration files with hardcoded credentials.
* **Persistence:** Locate startup folders for persistence mechanisms.
* **Data Exfiltration:** Identify large or important datasets for exfiltration.
* **Evasion:** Identify antivirus logs or security tools to bypass them.

***

#### 📌 **Common Techniques for File and Directory Discovery**

| **Technique**                  | **Command/Tool Example**                                           | **Description**                        |
| ------------------------------ | ------------------------------------------------------------------ | -------------------------------------- |
| **List Directories**           | `dir /s` (Windows), `ls -R` (Linux)                                | Recursive directory listing            |
| **Search for Sensitive Files** | `find / -name *.env`                                               | Search for specific file types         |
| **Locate Hidden Files**        | `ls -la`                                                           | Reveal hidden files                    |
| **Check Startup Folders**      | `dir C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Startup` | Identify persistence locations         |
| **System Configuration Files** | `cat /etc/passwd` (Linux)                                          | Extract system user information        |
| **PowerShell Enumeration**     | `Get-ChildItem -Recurse -Force`                                    | Recursive file discovery in PowerShell |

***

#### 📊 **Common Tools Used**

| **Tool**            | **Purpose**                                  |
| ------------------- | -------------------------------------------- |
| **PowerShell**      | Recursive file enumeration                   |
| **CMD (dir)**       | Directory listing                            |
| **Findstr**         | Search within files                          |
| **Find (Linux)**    | Search for files by name or type             |
| **grep (Linux)**    | Search within files                          |
| **Tree**            | Visual directory structure                   |
| **WinPEAS/LinPEAS** | Enumerate sensitive files and configurations |

***

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

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

**🕵️ Identify Suspicious File Searches**

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

**🕵️ Monitor Access to Sensitive Files**

```powershell
Get-ChildItem -Path "C:\Users\*" -Recurse -Include "*.env", "*.xml", "*.config", "*password*"
```

**🕵️ Check Recent File Access**

```powershell
Get-ChildItem -Path "C:\" -Recurse | Where-Object { $_.LastAccessTime -gt (Get-Date).AddHours(-24) }
```

**🕵️ Look for Hidden File Access**

```powershell
Get-ChildItem -Path "C:\" -Hidden -Recurse
```

***

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

**🕵️ Detect Directory Listing Commands**

```kql
DeviceProcessEvents
| where ProcessCommandLine contains "dir" or ProcessCommandLine contains "ls"
| project Timestamp, DeviceName, ProcessCommandLine, AccountName
```

**🕵️ Identify Sensitive File Access**

```kql
DeviceFileEvents
| where FileName matches regex ".*(password|config|credentials|backup).*"
| where ActionType == "FileAccessed"
| project Timestamp, DeviceName, FileName, FolderPath, AccountName
```

**🕵️ Monitor Recursive Directory Scans**

```kql
DeviceProcessEvents
| where ProcessCommandLine contains "-Recurse" or ProcessCommandLine contains "/s"
| project Timestamp, DeviceName, ProcessCommandLine, AccountName
```

**🕵️ Look for Startup Folder Access**

```kql
DeviceFileEvents
| where FolderPath contains "Startup"
| where ActionType == "FileAccessed"
| project Timestamp, DeviceName, FileName, FolderPath, AccountName
```

**🕵️ Track Access to System Configuration Files**

```kql
DeviceFileEvents
| where FileName contains "passwd" or FileName contains "shadow"
| project Timestamp, DeviceName, FileName, FolderPath, AccountName
```

***

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

| **Event ID** | **Description**                                         |
| ------------ | ------------------------------------------------------- |
| **4688**     | A new process was created (e.g., `dir`, `find`, `grep`) |
| **4663**     | Object access attempt (e.g., file read/write)           |
| **4660**     | An object was deleted                                   |
| **4656**     | A handle to an object was requested                     |

**📌 Focus on Event ID 4688:**

* Look for commands like:
  * `dir /s`
  * `ls -R`
  * `find / -name`
  * `grep password`

**📌 Focus on Event ID 4663:**

* Monitor file access activity:
  * `password.txt`
  * `config.xml`
  * `sensitive_data.zip`

***

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

#### 1️⃣ **Identify Suspicious File Access Commands**

* Search executed commands related to file discovery:

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

***

#### 2️⃣ **Trace Process Tree**

* Identify parent and child processes of discovery commands:

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

***

#### 3️⃣ **Inspect Access to Sensitive Folders**

* Check critical directories:

```powershell
Get-ChildItem -Path "C:\Users\*" -Recurse -Include "*.env", "*.xml", "*.config"
```

***

#### 4️⃣ **Identify Recently Accessed Files**

* List files accessed in the last 24 hours:

```powershell
Get-ChildItem -Path "C:\" -Recurse | Where-Object { $_.LastAccessTime -gt (Get-Date).AddDays(-1) }
```

***

#### 5️⃣ **Analyze Command History**

* Inspect PowerShell command history:

```powershell
(Get-PSReadlineOption).HistorySavePath | Get-Content
```

***

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

#### 📌 **1. Revoke Unnecessary File Permissions**

```powershell
icacls "C:\SensitiveFolder" /inheritance:r
```

#### 📌 **2. Monitor Critical Directories**

* Enable File Integrity Monitoring (FIM).

#### 📌 **3. Quarantine Suspicious Processes**

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

#### 📌 **4. Remove Unauthorized Access**

* Disable compromised accounts:

```powershell
Disable-LocalUser -Name "suspiciousUser"
```

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

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

***

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

1. **Enable File Auditing:**
   * Monitor **Event IDs 4663, 4688**.
2. **Implement Least Privilege Access:**
   * Limit access to sensitive folders.
3. **Monitor Sensitive File Access:**
   * Alert on unauthorized access to files like `password.txt`, `config.xml`.
4. **Disable Command-Line Access for Non-Admins:**
   * Restrict tools like `cmd.exe`, `powershell.exe`.
5. **Use File Integrity Monitoring (FIM):**
   * Detect unauthorized changes to sensitive files.
6. **Educate Users:**
   * Train users to recognize unauthorized file access patterns.

***

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

* **File Discovery is Often Reconnaissance:** Attackers seek sensitive data before launching further attacks.
* **Focus on Command-Line Patterns:** Commands like `dir /s`, `ls -R`, `find /` are key indicators.
* **Audit Sensitive Folders:** Regularly monitor access and modifications.
* **Implement File Integrity Monitoring (FIM):** Detect unauthorized file access.
* **Enforce Least Privilege Principle:** Restrict file access to only necessary users.

***

## 🚨 **Persistence via Registry Run Keys/Startup Folder**

***

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

#### 📝 **What is Persistence via Registry Run Keys/Startup Folder?**

* **Persistence** ensures an attacker maintains access to a compromised system across reboots or interruptions.
* Attackers often use:
  * **Registry Run Keys:** Automatically execute malicious code at system startup.
  * **Startup Folder:** Place malicious files in folders that run programs at user login.

#### 📑 **Why Attackers Use These Techniques?**

* **Stealth:** Blend into legitimate startup processes.
* **Reliability:** Ensure malware executes every time the system reboots.
* **Ease of Access:** Run keys and startup folders are often overlooked in security audits.
* **Flexibility:** Works across Windows versions and configurations.

***

#### 📌 **Common Techniques for Persistence**

| **Technique**             | **Description**                           | **Registry Key/Folder**                                                         |
| ------------------------- | ----------------------------------------- | ------------------------------------------------------------------------------- |
| **Registry Run Key**      | Run malicious code at startup.            | `HKCU\Software\Microsoft\Windows\CurrentVersion\Run`                            |
| **RunOnce Key**           | Run code only on the next startup.        | `HKCU\Software\Microsoft\Windows\CurrentVersion\RunOnce`                        |
| **Startup Folder**        | Add malicious files to startup directory. | `C:\Users\<User>\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup` |
| **Scheduled Tasks**       | Create scheduled tasks to execute code.   | `schtasks /create`                                                              |
| **Service Configuration** | Modify Windows service binaries.          | `HKLM\SYSTEM\CurrentControlSet\Services`                                        |

***

#### 📌 **Example Commands**

* **Add to Registry Run Key:**

```cmd
reg add "HKCU\Software\Microsoft\Windows\CurrentVersion\Run" /v MaliciousKey /t REG_SZ /d "C:\malware.exe"
```

* **Add to Startup Folder:**

```cmd
copy C:\malware.exe "C:\Users\<User>\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup"
```

* **Add to RunOnce Key:**

```cmd
reg add "HKCU\Software\Microsoft\Windows\CurrentVersion\RunOnce" /v Update /t REG_SZ /d "C:\malware.exe"
```

***

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

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

**🕵️ Check Run and RunOnce Registry Keys**

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

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

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

**🕵️ Check Scheduled Tasks for Suspicious Entries**

```powershell
Get-ScheduledTask | Where-Object { $_.TaskPath -like "*Update*" }
```

**🕵️ Check Service Binaries for Suspicious Paths**

```powershell
Get-WmiObject Win32_Service | Select-Object Name, PathName | Where-Object { $_.PathName -like "*Temp*" }
```

***

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

**🕵️ Detect Registry Key Modifications**

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

**🕵️ Detect Startup Folder Modifications**

```kusto
DeviceFileEvents
| where FolderPath contains "Startup"
| where ActionType == "FileCreated" or ActionType == "FileModified"
| project Timestamp, DeviceName, FolderPath, FileName, AccountName
```

**🕵️ Identify Suspicious Service Configurations**

```kusto
DeviceRegistryEvents
| where RegistryKey contains "SYSTEM\\CurrentControlSet\\Services"
| where RegistryValueData contains "Temp" or RegistryValueData contains ".exe"
| project Timestamp, DeviceName, RegistryKey, RegistryValueName, RegistryValueData
```

**🕵️ Monitor Processes Executing from Startup Locations**

```kusto
DeviceProcessEvents
| where FolderPath contains "Startup"
| where FileName endswith ".exe" or FileName endswith ".bat"
| project Timestamp, DeviceName, FileName, FolderPath, ProcessCommandLine, AccountName
```

***

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

| **Event ID** | **Description**                                 |
| ------------ | ----------------------------------------------- |
| **4657**     | A registry value was modified.                  |
| **4688**     | A new process was created.                      |
| **4697**     | A service was installed in the system.          |
| **4663**     | Object access attempt (Startup Folder changes). |

**📌 Focus on Event ID 4657:**

* Look for modifications to:
  * `HKCU:\Software\Microsoft\Windows\CurrentVersion\Run`
  * `HKCU:\Software\Microsoft\Windows\CurrentVersion\RunOnce`

**📌 Focus on Event ID 4688:**

* Look for processes running from:
  * `C:\Users\<User>\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup`

**📌 Focus on Event ID 4697:**

* Check for newly installed services.

***

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

#### 1️⃣ **Identify Malicious Registry Entries**

* Look for unexpected keys in `Run` or `RunOnce`:

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

***

#### 2️⃣ **Analyze Startup Folder**

* Identify suspicious files:

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

***

#### 3️⃣ **Trace Malicious Processes**

* Correlate process activity:

```powershell
Get-EventLog -LogName Security -InstanceId 4688 | Select-String "Startup"
```

***

#### 4️⃣ **Inspect Services for Persistence**

* Review service binaries:

```powershell
Get-WmiObject Win32_Service | Where-Object { $_.PathName -like "*Temp*" }
```

***

#### 5️⃣ **Review Scheduled Tasks**

* Look for unusual scheduled tasks:

```powershell
Get-ScheduledTask | Where-Object { $_.TaskPath -like "*Update*" }
```

***

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

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

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

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

```powershell
Remove-Item -Path "C:\Users\<User>\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup\malware.exe"
```

#### 📌 **3. Disable Malicious Services**

```powershell
sc stop "MaliciousService"
sc delete "MaliciousService"
```

#### 📌 **4. Terminate Suspicious Processes**

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

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

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

***

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

1. **Enable Registry Auditing:**
   * Monitor **Event ID 4657** for `Run` and `RunOnce`.
2. **Restrict Startup Folder Access:**
   * Limit write permissions to startup folders.
3. **Use Least Privilege Principle:**
   * Restrict admin rights to essential users.
4. **Enable Application Control Policies:**
   * Block untrusted applications via **AppLocker**.
5. **Monitor Suspicious Scheduled Tasks:**
   * Periodically audit scheduled tasks.
6. **Regular Patching:**
   * Keep systems and software updated.

***

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

* **Registry Run Keys and Startup Folders are Common Persistence Mechanisms:** Monitor them closely.
* **Event IDs 4657, 4688, 4697 Are Crucial:** Set up alerts for modifications.
* **Audit Regularly:** Periodically inspect registry keys and startup folders.
* **Enforce Application Whitelisting:** Use tools like AppLocker.

***

## 🚨 **Valid Accounts: Default Accounts**

***

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

#### 📝 **What is Default Account Exploitation?**

* **Default Accounts** are built-in user accounts that come preconfigured with operating systems, applications, and network devices (e.g., `Administrator`, `Guest`, `sa` for SQL Server).
* Attackers exploit these accounts if:
  * **Default credentials remain unchanged**.
  * Accounts are **enabled by default**.
  * Accounts have **excessive privileges**.
  * **Weak passwords** are set for these accounts.

***

#### 📑 **Why Attackers Target Default Accounts?**

* **Easy Access:** Many systems are deployed without disabling default accounts.
* **Privilege Escalation:** Default accounts often have administrative or privileged access.
* **Persistence:** Attackers use default accounts to maintain long-term access.
* **Stealth:** Legitimate accounts are less likely to trigger alerts.

***

#### 📌 **Common Default Accounts and Services**

| **Default Account** | **Platform/Service**              | **Purpose**          |
| ------------------- | --------------------------------- | -------------------- |
| **Administrator**   | Windows Systems                   | System Administrator |
| **root**            | Linux/Unix Systems                | Superuser Access     |
| **sa**              | SQL Server                        | Database Admin       |
| **admin**           | Network Devices (Cisco, Fortinet) | Device Admin         |
| **Guest**           | Windows Systems                   | Restricted Access    |
| **postgres**        | PostgreSQL Database               | Database Admin       |
| **pi**              | Raspberry Pi                      | Device Admin         |

***

#### 📌 **Common Techniques for Exploiting Default Accounts**

| **Technique**                | **Description**                       | **Example Command**                        |
| ---------------------------- | ------------------------------------- | ------------------------------------------ |
| **Brute Force Attack**       | Guess passwords for default accounts. | `hydra -l admin -P passwords.txt <target>` |
| **Default Credential Login** | Use known default credentials.        | `ssh root@<IP>`                            |
| **Account Misconfiguration** | Exploit accounts left enabled.        | `net user Administrator`                   |
| **SQL Default Account**      | Exploit `sa` accounts in SQL Server.  | `sqlcmd -S <server> -U sa`                 |
| **Remote Access via Admin**  | Use default accounts over RDP/SSH.    | `mstsc /v:<IP>`                            |

***

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

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

**🕵️ List Default Accounts in Windows**

```powershell
Get-LocalUser | Where-Object { $_.Name -in @("Administrator", "Guest") }
```

**🕵️ Check if Default Accounts Are Enabled**

```powershell
Get-LocalUser | Where-Object { $_.Enabled -eq $true }
```

**🕵️ List Accounts with Elevated Privileges**

```powershell
Get-LocalGroupMember -Group "Administrators"
```

**🕵️ Check Recent Login Activity for Default Accounts**

```powershell
Get-EventLog -LogName Security -InstanceId 4624 | Where-Object { $_.Message -like "*Administrator*" }
```

***

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

**🕵️ Detect Default Account Logins**

```kusto
SecurityEvent
| where EventID == 4624
| where AccountName in ("Administrator", "Guest", "sa", "root", "admin")
| project Timestamp, AccountName, IpAddress, LogonType, DeviceName
```

**🕵️ Identify Brute Force Attempts on Default Accounts**

```kusto
SecurityEvent
| where EventID == 4625
| where AccountName in ("Administrator", "Guest", "sa", "root", "admin")
| summarize FailedAttempts = count() by AccountName, IpAddress
| where FailedAttempts > 5
```

**🕵️ Detect Default Account Modifications**

```kusto
DeviceRegistryEvents
| where RegistryKey contains "SAM"
| where ActionType == "RegistryValueSet"
| project Timestamp, DeviceName, RegistryKey, AccountName
```

**🕵️ Monitor Default SQL Account Logins (`sa`)**

```kusto
DeviceProcessEvents
| where ProcessCommandLine contains "sqlcmd"
| where ProcessCommandLine contains "-U sa"
| project Timestamp, DeviceName, ProcessCommandLine, AccountName
```

**🕵️ Identify Default Accounts Used for Remote Access**

```kusto
DeviceNetworkEvents
| where RemotePort in (3389, 22)
| where AccountName in ("Administrator", "root", "admin")
| project Timestamp, DeviceName, RemoteIP, RemotePort, AccountName
```

***

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

| **Event ID** | **Description**                                          |
| ------------ | -------------------------------------------------------- |
| **4624**     | Successful login (Default accounts are often listed).    |
| **4625**     | Failed login attempt (Repeated attempts are suspicious). |
| **4720**     | User account created.                                    |
| **4728**     | User added to privileged group.                          |
| **4732**     | User added to global group.                              |

**📌 Focus on Event ID 4624:**

* Look for logins from:
  * `Administrator`
  * `Guest`
  * `sa`
  * `root`

**📌 Focus on Event ID 4728:**

* Look for additions to groups like:
  * `Administrators`
  * `Domain Admins`

***

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

#### 1️⃣ **Identify Enabled Default Accounts**

```powershell
Get-LocalUser | Where-Object { $_.Name -in @("Administrator", "Guest") -and $_.Enabled -eq $true }
```

***

#### 2️⃣ **Trace Account Activity**

* Check event logs for recent usage:

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

***

#### 3️⃣ **Review Remote Access Logs**

* Investigate remote sessions:

```powershell
Get-EventLog -LogName Security -InstanceId 4624 | Where-Object { $_.Message -like "*RDP*" }
```

***

#### 4️⃣ **Check SQL Server Login Logs**

* Verify `sa` account activity:

```sql
SELECT login_time, host_name, program_name FROM sys.dm_exec_sessions WHERE login_name = 'sa';
```

***

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

#### 📌 **1. Disable Unused Default Accounts**

```powershell
Disable-LocalUser -Name "Administrator"
```

#### 📌 **2. Enforce Strong Passwords for Default Accounts**

```powershell
net user Administrator StrongP@ssw0rd!
```

#### 📌 **3. Remove Default Accounts from Admin Groups**

```powershell
Remove-LocalGroupMember -Group "Administrators" -Member "Administrator"
```

#### 📌 **4. Monitor SQL Server `sa` Account**

* Disable `sa` if not required:

```sql
ALTER LOGIN sa DISABLE;
```

#### 📌 **5. Enable Account Lockout Policies**

```powershell
net accounts /lockoutthreshold:5
```

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

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

***

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

1. **Disable Default Accounts if Not Required:**
   * Disable accounts like `Administrator`, `Guest`, and `sa`.
2. **Enforce Strong Password Policies:**
   * Ensure default accounts have strong, unique passwords.
3. **Monitor Default Account Activity:**
   * Alert on usage of default accounts in remote sessions or privileged tasks.
4. **Limit Default Account Permissions:**
   * Remove default accounts from sensitive groups.
5. **Use Multi-Factor Authentication (MFA):**
   * Add MFA to privileged accounts.
6. **Audit Regularly:**
   * Periodically review account usage logs and group memberships.

***

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

* **Default Accounts are Low-Hanging Fruit:** Attackers often target them first.
* **Disable Unused Accounts:** Remove or disable accounts like `Administrator` and `Guest`.
* **Monitor Account Activity:** Use **Event IDs 4624, 4625, 4728**.
* **Enforce Strong Passwords:** Always change default passwords.
* **Use Multi-Factor Authentication:** Secure critical accounts with MFA.

***

## 🚨 **Data Transfer Size Limits**

***

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

#### 📝 **What is Data Transfer Size Limit Abuse?**

* Attackers often **manipulate data transfer limits** to **evade detection** while exfiltrating large volumes of data from a compromised network.
* By transferring data in smaller chunks or obfuscating file sizes, attackers can bypass **Data Loss Prevention (DLP)** controls and avoid raising red flags.

***

#### 📑 **Why Attackers Manipulate Data Transfer Size?**

* **Avoid Detection:** Small or irregular data transfers may not trigger monitoring tools.
* **Evade Threshold Alerts:** Many DLP systems flag unusually large transfers.
* **Blend with Normal Traffic:** Break data into chunks to mimic typical user behavior.
* **Exfiltrate Large Volumes Over Time:** Steady, small transfers are harder to detect.

***

#### 📌 **Common Techniques for Data Transfer Size Manipulation**

| **Technique**              | **Description**                                                      | **Example Tools**      |
| -------------------------- | -------------------------------------------------------------------- | ---------------------- |
| **Chunking**               | Split large data files into smaller pieces for gradual exfiltration. | `split`, `7zip`        |
| **Compression**            | Compress files to reduce size before transfer.                       | `gzip`, `WinRAR`       |
| **Encryption/Obfuscation** | Encrypt or encode data to hide its true size/type.                   | `openssl`, `base64`    |
| **Data Hiding**            | Embed data within other file types (e.g., images, PDFs).             | `steghide`, `ExifTool` |
| **Low-Bandwidth Channels** | Use slow protocols (e.g., DNS tunneling) to avoid suspicion.         | `dnscat2`, `iodine`    |
| **Alternate Protocols**    | Use FTP, SFTP, or HTTP for stealthy data transfer.                   | `curl`, `scp`          |

***

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

1. **Chunked Transfers Over FTP:** Files broken into small chunks and exfiltrated slowly.
2. **HTTP POST Data Exfiltration:** Small POST requests carrying encoded data.
3. **DNS Tunneling for Data Transfers:** Data exfiltrated over DNS queries.
4. **Email Attachment Abuse:** Data hidden in small email attachments.
5. **Cloud Services Abuse:** Small file uploads to cloud storage (e.g., Dropbox, Google Drive).

***

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

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

**🕵️ Monitor Unusual File Transfers**

```powershell
Get-ChildItem -Path "C:\Users\*\Documents" -Recurse | Where-Object { $_.Length -gt 10485760 }
```

* Flag files larger than **10MB**.

**🕵️ Monitor Recent Compressed Files**

```powershell
Get-ChildItem -Path "C:\*" -Include *.zip, *.rar, *.7z -Recurse | Where-Object { $_.LastWriteTime -gt (Get-Date).AddHours(-24) }
```

**🕵️ Inspect Network Connections for Large Transfers**

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

**🕵️ Check Outbound DNS Traffic for Large Payloads**

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

***

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

**🕵️ Detect Large File Transfers**

```kusto
DeviceFileEvents
| where ActionType == "FileCopied" or ActionType == "FileUploaded"
| where FileSize > 10485760 // Files larger than 10MB
| project Timestamp, DeviceName, FileName, FolderPath, AccountName, FileSize
```

**🕵️ Monitor Chunked Data Transfers Over HTTP**

```kusto
DeviceNetworkEvents
| where Protocol == "HTTP"
| where RemoteUrl contains "upload"
| summarize TotalDataTransferred = sum(NetworkBytesSent) by RemoteUrl, AccountName
| where TotalDataTransferred > 10485760
```

**🕵️ Identify Compressed File Transfers**

```kusto
DeviceFileEvents
| where FileName endswith ".zip" or FileName endswith ".rar" or FileName endswith ".7z"
| where ActionType == "FileCopied"
| project Timestamp, DeviceName, FileName, FolderPath, AccountName
```

**🕵️ Detect DNS Tunneling Activity**

```kusto
DeviceNetworkEvents
| where RemotePort == 53
| where NetworkBytesSent > 512
| summarize TotalDataTransferred = sum(NetworkBytesSent) by RemoteIP
| where TotalDataTransferred > 1048576
```

**🕵️ Monitor Email Attachments with Large Files**

```kusto
EmailEvents
| where AttachmentSize > 10485760
| project Timestamp, SenderEmailAddress, RecipientEmailAddress, AttachmentSize, FileName
```

***

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

| **Event ID** | **Description**                                              |
| ------------ | ------------------------------------------------------------ |
| **4663**     | Object Access: File copied or transferred.                   |
| **5156**     | Network connection allowed (large data transfers).           |
| **4688**     | Process creation (e.g., `curl`, `scp`).                      |
| **4104**     | PowerShell script block execution (e.g., `split`, `base64`). |
| **6005**     | DNS requests (DNS tunneling detection).                      |

**📌 Focus on Event ID 4663:**

* Look for unusual file access or copying activity:

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

**📌 Focus on Event ID 5156:**

* Look for outbound connections with large amounts of data transferred.

***

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

#### 1️⃣ **Analyze Network Traffic**

* Identify outbound traffic spikes to unknown destinations:

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

***

#### 2️⃣ **Inspect Compressed/Archived Files**

* Search for recent `.zip`, `.rar`, or `.7z` files:

```powershell
Get-ChildItem -Path "C:\*" -Include *.zip, *.rar, *.7z -Recurse
```

***

#### 3️⃣ **Trace DNS Queries for Data Transfer**

* Identify large DNS payloads:

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

***

#### 4️⃣ **Review HTTP/S Traffic for Repeated Small Transfers**

* Inspect log files for recurring patterns of file uploads.

***

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

#### 📌 **1. Block Malicious IPs**

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

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

```powershell
Move-Item -Path "C:\Users\*\Documents\large_archive.zip" -Destination "C:\Quarantine"
```

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

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

#### 📌 **4. Monitor DNS Traffic for Tunneling**

* Enable deep packet inspection on DNS traffic.

#### 📌 **5. Enable Data Loss Prevention (DLP) Policies**

* Apply limits to outbound file sizes.

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

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

***

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

1. **Enable Data Loss Prevention (DLP):**
   * Set thresholds for maximum file sizes.
2. **Implement Network Traffic Monitoring (NTM):**
   * Track large outbound connections.
3. **Monitor DNS Traffic:**
   * Detect DNS tunneling patterns.
4. **Block Unauthorized File Transfer Tools:**
   * Restrict tools like `curl`, `scp`, `ftp`.
5. **Encrypt Sensitive Files:**
   * Prevent plaintext data exfiltration.
6. **Implement Rate-Limiting Policies:**
   * Limit bandwidth for external file transfers.

***

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

* **Data Exfiltration Often Hides in Plain Sight:** Small, frequent transfers can go unnoticed.
* **DNS and HTTP/S Are Common Channels:** Monitor these protocols.
* **Compression and Obfuscation Are Common Tactics:** Look for `.zip`, `.rar`, and `.7z` files.
* **Enable DLP Policies:** Set file transfer thresholds.
* **Regular Auditing is Crucial:** Monitor logs, network traffic, and DNS queries.

***

## 🚨 **Process Doppelgängingysis**

***

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

#### 📝 **What is Process Doppelgänging?**

* **Process Doppelgänging** is an advanced **code injection technique** that **bypasses antivirus and endpoint protection** by exploiting the Windows NTFS transaction feature.
* It allows attackers to **create a malicious process** in a way that:
  * It **does not create a new file on disk**.
  * It **appears as a legitimate process**.
  * It **bypasses process monitoring tools**.

#### 📑 **Why Attackers Use Process Doppelgänging?**

* **Stealth:** Avoid detection by antivirus and monitoring tools.
* **Fileless Execution:** No malicious file needs to be saved on disk.
* **Privilege Escalation:** Run code with high privileges under a legitimate process name.
* **Persistence:** Maintain stealthy access across reboots.

***

#### 📌 **How Does Process Doppelgänging Work?**

1. **Transacted File Creation:** A malicious executable is written to disk using **Windows NTFS transactions**.
2. **Rollback Transaction:** The transaction is rolled back, making the file invisible.
3. **Process Creation:** The process is launched in a suspended state using the **rollback file**.
4. **Mapped Section Replacement:** Replace the memory section of the suspended process with malicious code.
5. **Process Execution:** Resume the process to execute the malicious payload.

#### 📌 **Common Tools for Process Doppelgänging**

| **Tool**           | **Purpose**                       |
| ------------------ | --------------------------------- |
| **Mimikatz**       | Credential theft                  |
| **Cobalt Strike**  | Post-exploitation framework       |
| **Metasploit**     | Exploitation and payload delivery |
| **Process Hacker** | Memory and process manipulation   |

***

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

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

**🕵️ Check for Suspicious Processes Running in Suspended State**

```powershell
Get-Process | Where-Object { $_.StartInfo.FileName -eq $null }
```

**🕵️ Inspect Processes Without Valid Executable Paths**

```powershell
Get-CimInstance Win32_Process | Where-Object { $_.ExecutablePath -eq $null }
```

**🕵️ Monitor NTFS Transactions**

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

**🕵️ Inspect Process Tree Anomalies**

```powershell
Get-WmiObject Win32_Process | Select-Object ProcessId, ParentProcessId, Name, CommandLine
```

***

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

**🕵️ Detect Suspended Processes with Malicious Command Line**

```kusto
DeviceProcessEvents
| where ProcessCreationTime > ago(1d)
| where ProcessIntegrityLevel == "System"
| where ProcessCommandLine contains "suspended"
| project Timestamp, DeviceName, ProcessCommandLine, ParentProcessName, AccountName
```

**🕵️ Look for NTFS Transaction Abuse**

```kusto
DeviceFileEvents
| where ActionType == "FileCreated"
| where FolderPath contains "NTFS"
| where FileName endswith ".tmp"
| project Timestamp, DeviceName, FileName, FolderPath, AccountName
```

**🕵️ Identify Process Injection via Doppelgänging**

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

**🕵️ Identify Suspicious Child Processes**

```kusto
DeviceProcessEvents
| where ParentProcessFileName in ("svchost.exe", "explorer.exe")
| where ProcessCommandLine contains ".exe"
| where ProcessCreationTime > ago(1d)
| project Timestamp, DeviceName, ProcessCommandLine, ParentProcessName, AccountName
```

**🕵️ Detect Memory Manipulation**

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

***

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

| **Event ID** | **Description**                            |
| ------------ | ------------------------------------------ |
| **4688**     | A new process was created.                 |
| **4656**     | A handle to an object was requested.       |
| **4663**     | An attempt was made to access an object.   |
| **142**      | NTFS transaction activity.                 |
| **592**      | A new process was created (older systems). |

**📌 Focus on Event ID 4688:**

* Look for:

  ```kusto
  ProcessCommandLine: NtCreateTransaction
  ParentProcess: svchost.exe, explorer.exe
  ```

**📌 Focus on Event ID 142:**

* Check NTFS transaction logs for suspicious activity.

**📌 Focus on Event ID 4663:**

* Look for access to unusual memory objects:

  ```makefile
  ObjectName: \Device\HarddiskVolumeShadowCopy
  ```

***

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

#### 1️⃣ **Trace Suspicious Processes**

* Identify parent-child process relationships:

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

***

#### 2️⃣ **Inspect Memory Regions**

* Check for suspicious memory sections in processes:

```powershell
Get-Process -Id <PID> | Select-Object Handles, NPM, PM, WS
```

***

#### 3️⃣ **Analyze NTFS Transactions**

* Investigate NTFS logs:

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

***

#### 4️⃣ **Check Recent Executable Activity**

* Identify recently created temporary executables:

```powershell
Get-ChildItem -Path "C:\Windows\Temp\" -Recurse -Include *.tmp, *.exe
```

***

#### 5️⃣ **Trace DLL Injections**

* List loaded DLLs for suspicious processes:

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

***

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

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

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

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

```powershell
Remove-Item -Path "C:\Windows\Temp\suspicious.exe" -Force
```

#### 📌 **3. Clear NTFS Transaction Logs**

```powershell
fsutil usn deletejournal /d /n c:
```

#### 📌 **4. Isolate Compromised Hosts**

* Disconnect the system from the network.

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

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

***

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

1. **Enable Windows Defender Advanced Threat Protection (ATP):**
   * Monitor advanced attack techniques.
2. **Enable Process Auditing:**
   * Monitor Event IDs **4688**, **4663**, **142**.
3. **Disable Unnecessary NTFS Features:**
   * Limit NTFS transactions if not required.
4. **Use Application Control (AppLocker/WDAC):**
   * Block untrusted binaries.
5. **Apply Patches and Updates:**
   * Keep Windows OS updated.
6. **Restrict Admin Privileges:**
   * Limit the ability to create NTFS transactions.
7. **Educate Admins and IT Staff:**
   * Raise awareness about fileless attacks.

***

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

* **Process Doppelgänging is Stealthy:** It bypasses traditional antivirus solutions.
* **Focus on NTFS Logs:** Event ID **142** can reveal NTFS transaction abuse.
* **Monitor Suspended Processes:** Check for processes with `VirtualAlloc` and `WriteProcessMemory`.
* **Use Threat Intelligence:** Stay updated on tools like **Mimikatz** and **Cobalt Strike**.
* **Implement Application Whitelisting:** Prevent untrusted binaries from executing.

***

## 🚨 **Spearphishing via Service: Advanced Threat Analysis**

***

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

#### 📝 **What is Spearphishing via Service?**

* **Spearphishing via Service** is a technique where attackers exploit **trusted third-party services (e.g., collaboration tools, cloud platforms, email services)** to deliver **malicious payloads** or **phishing links**.
* Common targets include:
  * **Microsoft 365 (Outlook, Teams, SharePoint)**
  * **Google Workspace (Gmail, Drive, Docs)**
  * **Cloud Storage Platforms (Dropbox, OneDrive, Box)**
  * **Communication Platforms (Slack, Discord)**

***

#### 📑 **Why Attackers Use Spearphishing via Service?**

* **Trusted Platforms:** Emails and links originating from known services bypass traditional security filters.
* **Spoofing Trust:** Legitimate domains increase user trust and click-through rates.
* **Bypass Email Security:** Emails from trusted domains are less likely to be flagged.
* **Credential Harvesting:** Fake login prompts on known services fool users.
* **Payload Delivery:** Malicious attachments or links are hosted on legitimate platforms.

***

#### 📌 **Common Techniques Used in Spearphishing via Service**

| **Technique**                 | **Description**                                  | **Example**                                 |
| ----------------------------- | ------------------------------------------------ | ------------------------------------------- |
| **Cloud Hosted Payloads**     | Malicious files hosted on cloud services.        | `https://drive.google.com/file/d/123xyz`    |
| **Fake Login Pages**          | Spoofed service login pages.                     | `https://microsoft-login.xyz`               |
| **Embedded Malicious Macros** | Documents with hidden malicious scripts.         | `Document.docm`                             |
| **URL Shorteners**            | Obscure malicious links.                         | `bit.ly/abc123`                             |
| **OAuth Token Theft**         | Abuse OAuth permissions for unauthorized access. | `https://accounts.google.com/o/oauth2/auth` |
| **Service Account Hijacking** | Compromise legitimate service accounts.          | Attacker takes over `user@domain.com`       |

***

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

1. **Malware via OneDrive Link:** A document hosted on OneDrive contains embedded malware.
2. **Phishing via Teams Message:** Fake login page sent through Microsoft Teams.
3. **OAuth Abuse in Google Workspace:** Attacker gains access via rogue OAuth app.
4. **Fake Dropbox Notification:** “Your document is ready, click here to view.”

***

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

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

**🕵️ Search Recent Suspicious Emails**

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

**🕵️ Monitor Downloads from Cloud Services**

```powershell
Get-ChildItem -Path "C:\Users\*\Downloads" | Where-Object { $_.LastWriteTime -gt (Get-Date).AddHours(-24) }
```

**🕵️ Check for Suspicious URLs in Logs**

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

**🕵️ Inspect Browser History for Suspicious Links**

```powershell
Get-ChildItem -Path "C:\Users\*\AppData\Local\Microsoft\Edge\User Data\Default\History"
```

***

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

**🕵️ Identify Suspicious URLs in Emails**

```kusto
EmailEvents
| where EmailDirection == "Inbound"
| where ThreatTypes contains "Phishing"
| where Url contains "drive.google.com" or Url contains "dropbox.com"
| project Timestamp, SenderEmailAddress, RecipientEmailAddress, ThreatTypes, Url
```

**🕵️ Detect Malicious Document Downloads**

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

**🕵️ Identify OAuth Token Abuse**

```kusto
CloudAppEvents
| where ActionType == "OAuthGrant"
| where AppDisplayName contains "Unknown"
| project Timestamp, AppDisplayName, AccountName, IpAddress
```

**🕵️ Monitor Microsoft Teams/Slack Activity**

```kusto
DeviceProcessEvents
| where ProcessCommandLine contains "teams.exe" or ProcessCommandLine contains "slack.exe"
| where ProcessCommandLine contains "http"
| project Timestamp, DeviceName, ProcessCommandLine, AccountName
```

**🕵️ Check for Suspicious File Execution**

```kusto
DeviceProcessEvents
| where FolderPath contains "Downloads"
| where ProcessCommandLine contains ".docm" or ProcessCommandLine contains ".js"
| project Timestamp, DeviceName, ProcessCommandLine, AccountName
```

***

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

| **Event ID** | **Description**                               |
| ------------ | --------------------------------------------- |
| **4688**     | A new process was created.                    |
| **4663**     | Object access attempt (e.g., file download).  |
| **4104**     | PowerShell script block logging.              |
| **5156**     | Network connection allowed (HTTP/S requests). |
| **1202**     | OAuth grant (Azure AD).                       |

**📌 Focus on Event ID 4688:**

* Look for:

  ```vbnet
  ProcessName: powershell.exe
  ProcessCommandLine: Invoke-WebRequest -Uri "https://malicious.link"
  ```

**📌 Focus on Event ID 4663:**

* File downloaded from:

  ```makefile
  FolderPath: C:\Users\<User>\Downloads
  FileType: .docm, .xlsm
  ```

***

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

#### 1️⃣ **Analyze Malicious URLs**

* Verify URL reputation:
  * **VirusTotal:** `https://www.virustotal.com`
  * **URLScan:** `https://urlscan.io`

***

#### 2️⃣ **Inspect OAuth Grants**

* Review recent OAuth permissions:

```powershell
Get-AzureADServicePrincipal -All $true
```

***

#### 3️⃣ **Trace Malicious Downloads**

* List recent downloads:

```powershell
Get-ChildItem -Path "C:\Users\*\Downloads"
```

* Check file hash:

```powershell
Get-FileHash -Path "C:\Users\User\Downloads\malware.docm"
```

***

#### 4️⃣ **Inspect User Activity**

* Review sign-in logs:

```kql
SigninLogs
| where AppDisplayName contains "Microsoft Teams"
| where Status == "Failure"
```

***

#### 5️⃣ **Check OAuth Audit Logs**

* Look for suspicious app grants:

```kql
AuditLogs
| where OperationName == "Consent to application"
```

***

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

#### 📌 **1. Revoke OAuth Permissions**

* Revoke malicious OAuth grants:

```powershell
Remove-AzureADServiceAppRoleAssignment
```

#### 📌 **2. Quarantine Malicious Files**

```powershell
Move-Item -Path "C:\Users\User\Downloads\malware.docm" -Destination "C:\Quarantine"
```

#### 📌 **3. Block Malicious URLs**

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

#### 📌 **4. Reset Compromised Accounts**

* Force password reset:

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

#### 📌 **5. Terminate Malicious Processes**

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

***

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

1. **Enable Safe Links and Safe Attachments (Microsoft 365):**
   * Prevent malicious URLs and attachments.
2. **Enforce Multi-Factor Authentication (MFA):**
   * Reduce credential theft risk.
3. **Block Macros by Default:**
   * Prevent execution of malicious macros.
4. **Restrict OAuth Consent:**
   * Require admin approval for OAuth permissions.
5. **Train Users:**
   * Educate employees about phishing indicators.
6. **Enable DLP (Data Loss Prevention):**
   * Monitor cloud-based file activities.

***

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

* **Spearphishing via Services Leverages Trust:** Hosted on legitimate services like OneDrive or Dropbox.
* **OAuth is a Growing Attack Vector:** Monitor app grants closely.
* **Focus on Event IDs:** **4688, 4663, 5156, 1202.**
* **Use Threat Intelligence Tools:** Validate links with **VirusTotal** and **URLScan**.
* **User Awareness is Key:** Continuous training is essential.

***
