> For the complete documentation index, see [llms.txt](https://muhammed-hatem.gitbook.io/muhammed-hatem/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://muhammed-hatem.gitbook.io/muhammed-hatem/summaries/sec-504-notes/sec504.1.md).

# Sec504.1

### <mark style="color:orange;">What is difference between \[event, log, flow, incident] ?</mark>

#### <mark style="color:blue;">**1. Event**</mark>

* **Definition**: An observable occurrence or change in a system, network, or application.
* **Nature**: Can be normal (e.g., a user login) or abnormal (e.g., a failed login attempt).
* **Examples**:
  * A server reboot.
  * A file being modified.
  * An email being sent.

#### <mark style="color:blue;">**2. Log**</mark>

* **Definition**: A recorded entry of an event, stored for auditing, debugging, or analysis.
* **Nature**: Passive records (text files, databases) that document what happened.
* **Examples**:
  * A security log showing login attempts.
  * A system log recording errors.
  * An application log tracking user actions.

#### <mark style="color:blue;">**3. Flow (Network Flow)**</mark>

* **Definition**: A sequence of related network communications (e.g., traffic between two IPs).
* **Nature**: Represents data movement (e.g., NetFlow, sFlow).
* **Examples**:
  * A TCP/IP session between a client and server.
  * Data packets exchanged in a video call.

#### <mark style="color:blue;">**4. Incident**</mark>

* **Definition**: A harmful or disruptive event that impacts security, operations, or services.
* **Nature**: Requires investigation and response (e.g., breaches, outages).
* **Examples**:
  * A ransomware attack encrypting files.
  * A DDoS attack crashing a website.
  * A data leak exposing customer info.

#### <mark style="color:blue;">**Key Differences Summary**</mark>

| Term         | Description                    | Example                        |
| ------------ | ------------------------------ | ------------------------------ |
| **Event**    | Any observable occurrence      | User login, file deletion      |
| **Log**      | Record of events               | Security logs, error logs      |
| **Flow**     | Network communication data     | HTTP request/response          |
| **Incident** | Harmful event requiring action | Malware infection, data breach |

### [<mark style="color:orange;">Cyber killchain model</mark>](/muhammed-hatem/summaries/cyber-defence-frameworks/cyber-kill-chain.md) <mark style="color:orange;">?</mark>

#### *<mark style="color:blue;">Overview</mark>*

The **Cyber Kill Chain** (developed by Lockheed Martin) is a framework that models the stages of cyberattacks from initial reconnaissance to mission completion. Understanding each stage enables defenders to:

* **Detect attacks earlier** in the lifecycle
* **Disrupt attacker workflows** at critical points
* **Allocate resources effectively** based on threat intelligence

#### *<mark style="color:blue;">Attack Lifecycle & Defense</mark>*

<figure><img src="/files/Br2N03PUN9takAVSZQmo" alt=""><figcaption></figcaption></figure>

| Stage                | Attacker Actions                                      | Defender Procedures                                                    | Attacker Evasion Tactics                           |
| -------------------- | ----------------------------------------------------- | ---------------------------------------------------------------------- | -------------------------------------------------- |
| **1. Recon**         | <p>- OSINT research<br>- Network scanning</p>         | <p>- Threat intelligence<br>- Log analysis</p>                         | <p>- Use anonymous networks<br>- Slow scanning</p> |
| **2. Weaponization** | <p>- Create malware payload<br>- Exploit kits</p>     | <p>- Email filtering<br>- File sandboxing</p>                          | <p>- Polymorphic code<br>- Living-off-the-land</p> |
| **3. Delivery**      | <p>- Phishing emails<br>- Drive-by downloads</p>      | <p>- SPF/DMARC<br>- Web proxies</p>                                    | <p>- Domain rotation<br>- Encrypted C2</p>         |
| **4. Exploitation**  | <p>- Exploit vulnerabilities<br>- Macro attacks</p>   | <p>- Patch management<br>- Application whitelisting</p>                | <p>- Zero-day exploits<br>- Fileless attacks</p>   |
| **5. Installation**  | <p>- Malware droppers<br>- Persistence mechanisms</p> | <p>- EDR solutions<br>- Memory forensics (<code>Volatility</code>)</p> | <p>- Memory-only payloads<br>- Rootkits</p>        |
| **6. C2**            | <p>- Beaconing<br>- Remote access</p>                 | <p>- Network segmentation<br>- IDS/IPS</p>                             | <p>- Domain fronting<br>- Fast-flux DNS</p>        |
| **7. Actions**       | <p>- Data exfiltration<br>- Ransomware</p>            | <p>- DLP systems<br>- Backup policies</p>                              | <p>- Steganography<br>- Timed delays</p>           |

### <mark style="color:orange;">**Incident Response (IR) Plan ?**</mark>

An **Incident Response (IR) Plan** is a structured approach to identifying, managing, and recovering from cybersecurity incidents (e.g., data breaches, ransomware attacks, insider threats). It minimizes damage, reduces recovery time, and ensures compliance with legal requirements (e.g., GDPR, HIPAA).

The most widely adopted framework is **NIST SP 800-61**, which outlines **6 key phases** of incident response.

<figure><img src="/files/826BbizczM4mdKuA9YFx" alt="" width="496"><figcaption></figcaption></figure>

#### <mark style="color:blue;">**Why Use an IR Plan?**</mark>

1. **Minimize Damage**: Quickly contain and mitigate threats.
2. **Reduce Downtime**: Faster recovery = lower financial losses.
3. **Legal & Regulatory Compliance**: Avoid fines (e.g., GDPR penalties).
4. **Preserve Evidence**: Critical for forensic investigations.
5. **Improve Future Defenses**: Learn from past incidents.

#### <mark style="color:blue;">**6 Phases of Incident Response (Detailed Breakdown)**</mark>

#### <mark style="color:green;">**1. Preparation**</mark>

**Goal**: Ensure readiness before an incident occurs.

**Key Activities**:\
✔ **Policy Development**: Define roles (CSIRT team), escalation paths.\
✔ **Tools & Resources**: Deploy SIEM, EDR, forensic tools.\
✔ **Training & Drills**: Conduct tabletop exercises (e.g., mock ransomware attack).\
✔ **Backups & Recovery Plans**: Ensure secure, tested backups.

**Example**:

* A company trains employees to recognize phishing emails and sets up a **24/7 SOC** (Security Operations Center).

***

#### <mark style="color:green;">**2. Identification**</mark>

**Goal**: Detect and confirm a security incident.

**Key Activities**:\
✔ **Log Analysis**: Review SIEM alerts (e.g., unusual login attempts).\
✔ **Endpoint Detection**: Flag malware via EDR (e.g., CrowdStrike).\
✔ **User Reports**: Employees report suspicious activity.

**Example**:

* An IDS detects **unusual data exfiltration** from a database, triggering an investigation.

***

#### <mark style="color:green;">**3. Containment**</mark>

**Goal**: Isolate the threat to prevent further damage.

**Types of Containment**:

* **Short-term (Immediate)**: Disconnect infected systems from the network.
* **Long-term (Permanent)**: Patch vulnerabilities, reset credentials.

**Example**:

* A ransomware attack is detected → IT **disables network shares** and **isolates infected machines**.

***

#### <mark style="color:green;">**4. Eradication**</mark>

**Goal**: Remove the root cause of the incident.

**Key Activities**:\
✔ **Malware Removal**: Delete malicious files, terminate processes.\
✔ **Patch Vulnerabilities**: Fix exploited software flaws.\
✔ **Password Resets**: Change compromised credentials.

**Example**:

* After a phishing attack, the IR team **removes the malicious email** and **revokes stolen session tokens**.

***

#### <mark style="color:green;">**5. Recovery**</mark>

**Goal**: Restore systems safely to normal operations.

**Key Activities**:\
✔ **System Restoration**: Use clean backups (verify integrity).\
✔ **Monitoring**: Check for signs of reinfection.\
✔ **Gradual Reintroduction**: Bring systems online in stages.

**Example**:

* After a DDoS attack, services are **restored incrementally** while monitoring traffic for anomalies.

***

#### <mark style="color:green;">**6. Lessons Learned (Post-Incident Review)**</mark>

**Goal**: Improve future response efforts.

**Key Activities**:\
✔ **Incident Report**: Document timeline, impact, and actions taken.\
✔ **Root Cause Analysis (RCA)**: Identify weaknesses (e.g., unpatched servers).\
✔ **Update IR Plan**: Refine procedures based on findings.

**Example**:

* A breach occurred due to a misconfigured cloud bucket → Company **implements stricter access controls** and **enhances logging**.

***

#### <mark style="color:blue;">**Real-World IR Example: Equifax Breach (2017)**</mark>

1. **Preparation Failure**: Unpatched Apache Struts vulnerability.
2. **Identification Delay**: Attackers accessed data for **76 days** before detection.
3. **Containment**: Systems taken offline, but data was already stolen.
4. **Eradication**: Patched servers, but reputational damage was done.
5. **Recovery**: Cost **$1.4B+** in fines and remediation.
6. **Lessons Learned**: Better patch management, real-time monitoring.

***

#### <mark style="color:blue;">**IR Plan vs. Cyber Kill Chain**</mark>

| **Aspect**   | **IR Plan**          | **Cyber Kill Chain**        |
| ------------ | -------------------- | --------------------------- |
| **Purpose**  | Respond to incidents | Understand attack lifecycle |
| **Focus**    | Defense & recovery   | Offensive attack stages     |
| **Use Case** | After breach occurs  | Before/during attack        |

#### <mark style="color:orange;">**What is Scoping in Cybersecurity?**</mark>

**Scoping** refers to defining the **boundaries, objectives, and limitations** of a security assessment, investigation, or incident response effort. It ensures that efforts are focused, resources are allocated efficiently, and stakeholders have clear expectations.

***

#### <mark style="color:blue;">**Types of Scoping in Cybersecurity**</mark>

<mark style="color:green;">**1. Incident Response Scoping**</mark>

* **Goal**: Determine the **extent of a security incident** (e.g., breach, malware infection).
* **Key Questions**:
  * Which systems/networks are affected?
  * What data was compromised?
  * How far did the attacker penetrate?
* **Example**:
  * After detecting ransomware, the IR team scopes the attack to **only 3 servers**, preventing unnecessary shutdowns.

<mark style="color:green;">**2. Vulnerability Assessment/Penetration Testing Scoping**</mark>

* **Goal**: Define what systems, apps, or networks will be tested.
* **Key Questions**:
  * Is it a **black-box** (external) or **white-box** (internal) test?
  * Are **social engineering** attacks included?
  * What are the **rules of engagement** (e.g., no DDoS testing)?
* **Example**:
  * A pentest scope may exclude **production databases** to avoid disruptions.

<mark style="color:green;">**3. Compliance Audit Scoping**</mark>

* **Goal**: Identify which systems fall under regulatory requirements (e.g., GDPR, HIPAA).
* **Key Questions**:
  * Which departments handle **sensitive data**?
  * Are third-party vendors included?
* **Example**:
  * A PCI DSS audit scopes **only systems handling credit card data**.

<mark style="color:green;">**4. Forensic Investigation Scoping**</mark>

* **Goal**: Determine the **timeline, evidence sources, and legal constraints** of an investigation.
* **Key Questions**:
  * Which logs, devices, or cloud services need analysis?
  * Is this for **internal review** or **legal prosecution**?
* **Example**:
  * A data leak investigation scopes **email logs, file access records, and employee workstations**.

***

#### <mark style="color:blue;">**Why is Scoping Important?**</mark>

✔ **Prevents Scope Creep** (uncontrolled expansion of tasks).\
✔ **Saves Time & Resources** by avoiding unnecessary analysis.\
✔ **Ensures Legal & Compliance Alignment** (e.g., avoiding unauthorized scans).\
✔ **Sets Clear Expectations** for stakeholders (management, clients, legal teams).

***

#### <mark style="color:blue;">**Challenges in Scoping**</mark>

❌ **Over-Scoping**: Wasting effort on irrelevant systems.\
❌ **Under-Scoping**: Missing critical attack surfaces.\
❌ **Dynamic Environments**: Cloud & IoT make scoping harder.

***

#### <mark style="color:blue;">**Example: Scoping a Ransomware Attack**</mark>

1. **Initial Alert**: Encryption detected on **Finance Dept. files**.
2. **Scoping Steps**:
   * Check if other departments are affected.
   * Identify patient zero (e.g., phishing email).
   * Determine if backups were compromised.
3. **Result**: Attack contained to **one file server**, backups intact.

***

#### <mark style="color:blue;">**Scoping vs. Triage**</mark>

| **Scoping**                           | **Triage**                                            |
| ------------------------------------- | ----------------------------------------------------- |
| Defines **what** to analyze           | Prioritizes **urgency** of issues                     |
| Done **before** deep investigation    | Happens **during initial response**                   |
| Example: "Scan only Windows servers." | Example: "Critical systems first, then workstations." |

#### <mark style="color:orange;">**PowerShell vs. CMD ?**</mark>

Both **PowerShell** and **CMD (Command Prompt)** are command-line interfaces in Windows, but they serve different purposes and have distinct capabilities.

***

#### <mark style="color:blue;">**1. Overview**</mark>

| Feature                | **PowerShell**                           | **CMD (Command Prompt)**               |
| ---------------------- | ---------------------------------------- | -------------------------------------- |
| **Type**               | Advanced scripting language & shell      | Simple command interpreter             |
| **Introduced**         | 2006 (Windows PowerShell)                | 1981 (MS-DOS)                          |
| **Purpose**            | Automation, scripting, system management | Basic file operations, legacy commands |
| **Underlying Tech**    | .NET Framework                           | Win32 API                              |
| **Default in Windows** | Yes (since Win10)                        | Still available but deprecated         |

***

#### <mark style="color:blue;">**2. Key Differences**</mark>

**🔹 Language & Scripting**

* **PowerShell**:
  * Uses **object-oriented scripting** (outputs structured objects, not just text).
  * Supports **pipelining** (passing objects between commands).
  * Example:

```powershell
Get-Process | Where-Object { $_.CPU -gt 50 } | Stop-Process
```

#### **CMD**:

* **Text-based**, limited scripting (`.bat` files).
* Example:

```sh
tasklist | find "chrome"
```

### <mark style="color:orange;">**PowerShell Basic Syntax Cheat Sheet ?**</mark>

PowerShell is a powerful scripting language with a consistent verb-noun syntax. Here's a breakdown of its fundamental syntax elements:

#### <mark style="color:blue;">**1. Basic Command Structure**</mark>

```powershell
Verb-Noun [-Parameter] [Argument]
```

* **Verbs**: `Get-`, `Set-`, `New-`, `Remove-`, `Start-`, `Stop-`
* **Nouns**: `Process`, `Service`, `Item`, `Content`

**Example:**

```powershell
Get-Process -Name "chrome"  # Gets all Chrome processes
```

***

#### <mark style="color:blue;">**2. Variables**</mark>

* Declare with `$`:

  ```powershell
  $name = "John"
  $processes = Get-Process
  ```
* Use `${}` for complex names:

  ```powershell
  ${user name} = "Alice"
  ```

***

#### <mark style="color:blue;">**3. Pipelining (**</mark><mark style="color:blue;">**`|`**</mark><mark style="color:blue;">**)**</mark>

Pass output from one cmdlet to another:

```powershell
Get-Process | Where-Object { $_.CPU -gt 50 } | Stop-Process
```

* `$_` = Current object in the pipeline.

***

#### <mark style="color:blue;">**4. Comments**</mark>

* Single-line:

  ```powershell
  # This is a comment
  ```
* Multi-line:

  ```powershell
  <#
    This is a
    multi-line comment
  #>
  ```

***

#### <mark style="color:blue;">**5. Comparison Operators**</mark>

| Operator | Meaning        | Example            |
| -------- | -------------- | ------------------ |
| `-eq`    | Equal          | `$x -eq 5`         |
| `-ne`    | Not equal      | `$x -ne 5`         |
| `-gt`    | Greater than   | `$x -gt 10`        |
| `-lt`    | Less than      | `$x -lt 10`        |
| `-like`  | Wildcard match | `$name -like "A*"` |

***

#### <mark style="color:blue;">**6. Loops**</mark>

<mark style="color:green;">**For Loop**</mark>

```powershell
for ($i = 1; $i -le 5; $i++) {
    Write-Output "Number: $i"
}
```

<mark style="color:green;">**Foreach Loop**</mark>

```powershell
$services = Get-Service
foreach ($service in $services) {
    Write-Output $service.Name
}
```

<mark style="color:green;">**While Loop**</mark>

```powershell
$count = 1
while ($count -le 3) {
    Write-Output "Count: $count"
    $count++
}
```

***

#### <mark style="color:blue;">**7. Conditionals (**</mark><mark style="color:blue;">**`if`**</mark><mark style="color:blue;">**,**</mark><mark style="color:blue;">**&#x20;**</mark><mark style="color:blue;">**`else`**</mark><mark style="color:blue;">**,**</mark><mark style="color:blue;">**&#x20;**</mark><mark style="color:blue;">**`switch`**</mark><mark style="color:blue;">**)**</mark>

<mark style="color:green;">**If-Else**</mark>

```powershell
if ($age -ge 18) {
    Write-Output "Adult"
} else {
    Write-Output "Minor"
}
```

<mark style="color:green;">**Switch**</mark>

```powershell
$day = "Monday"
switch ($day) {
    "Monday"    { Write-Output "Start of week" }
    "Friday"    { Write-Output "Weekend soon" }
    default     { Write-Output "Midweek" }
}
```

***

#### <mark style="color:blue;">**8. Functions**</mark>

```powershell
function Greet($name) {
    Write-Output "Hello, $name!"
}
Greet -name "Alice"
```

<mark style="color:green;">**With Parameters:**</mark>

```powershell
function Add-Numbers($a, $b) {
    return $a + $b
}
Add-Numbers -a 5 -b 3  # Returns 8
```

***

#### <mark style="color:blue;">**9. Arrays & Hashtables**</mark>

<mark style="color:green;">**Arrays**</mark>

```powershell
$fruits = @("Apple", "Banana", "Cherry")
$fruits[0]  # "Apple"
```

<mark style="color:green;">**Hashtables (Key-Value Pairs)**</mark>

```powershell
$person = @{
    Name = "John"
    Age  = 30
}
Write-Output $person.Name  # "John"
```

***

#### <mark style="color:blue;">**10. File Operations**</mark>

| Cmdlet        | Description          |
| ------------- | -------------------- |
| `Get-Content` | Read a file          |
| `Set-Content` | Write to a file      |
| `Copy-Item`   | Copy files/folders   |
| `Remove-Item` | Delete files/folders |

<mark style="color:green;">**Example:**</mark>

```powershell
Get-Content "C:\logs\error.txt"  # Read file
Set-Content "C:\output.txt" "Hello, World!"  # Write file
```

***

#### <mark style="color:blue;">**11. Error Handling (**</mark><mark style="color:blue;">**`Try/Catch`**</mark><mark style="color:blue;">**)**</mark>

```powershell
try {
    Get-Item "C:\nonexistent.txt" -ErrorAction Stop
}
catch {
    Write-Output "Error: $_"
}
```

***

#### <mark style="color:blue;">**12. Running External Commands**</mark>

```powershell
# Run CMD commands
ipconfig /all

# Run EXE files
Start-Process "notepad.exe"
```

***

#### <mark style="color:blue;">**13. Help & Discovery**</mark>

| Command       | Description                    |
| ------------- | ------------------------------ |
| `Get-Help`    | Show cmdlet documentation      |
| `Get-Command` | List available cmdlets         |
| `Get-Member`  | List object properties/methods |

<mark style="color:green;">**Example**</mark>**:**

```powershell
Get-Help Get-Process  # Show help for Get-Process
Get-Command -Noun "Service"  # List all Service-related cmdlets
```

***

#### <mark style="color:blue;">**PowerShell vs. CMD Quick Reference**</mark>

| Task         | **PowerShell**                  | **CMD**                    |
| ------------ | ------------------------------- | -------------------------- |
| List files   | `Get-ChildItem`                 | `dir`                      |
| Kill process | `Stop-Process -Name "notepad"`  | `taskkill /IM notepad.exe` |
| Find text    | `Select-String "error" log.txt` | `find "error" log.txt`     |

***

#### <mark style="color:blue;">**Final Notes**</mark>

* **PowerShell is case-insensitive** (`Get-Process` = `get-process`).
* **Use `;` to separate commands on one line**:

  ```powershell
  $a = 5; $b = 10; $a + $b
  ```
* **Press `Tab` for auto-completion**.

## <mark style="color:orange;">Live examination ?</mark>

Live examinations in cybersecurity serve distinct purposes **before** and **after** a compromise, focusing on **preventive testing** and **post-breach analysis**, respectively. Below is a detailed breakdown of their roles, methodologies, and tools.

### <mark style="color:blue;">**1- Examining Processes with WMIC**</mark>

&#x20;**(Windows Management Instrumentation Command-Line)**

WMIC is a powerful command-line tool in Windows for querying system information, including running processes. While being deprecated in newer Windows versions (replaced by PowerShell's `Get-Process`), it remains useful for quick process analysis in legacy systems.

***

#### **1. Basic WMIC Commands for Process Examination**

#### **List All Running Processes**

```bash
wmic process list brief
```

* Shows: **Process Name, PID, Memory Usage, Executable Path**

#### **Get Detailed Process Info**

```bash
wmic process list full
```

* Displays: **Command line, parent PID, creation date, user context**

#### **Find a Specific Process**

```bash
wmic process where name="explorer.exe" list full
```

* Replace `explorer.exe` with your target process.

***

#### **2. Advanced Process Analysis**

#### **Check Process Executable Path**

```bash
wmic process get name,executablepath
```

* Useful for detecting **malware masquerading as legit processes**.

#### **View Process Memory Usage**

```bash
wmic process get name,workingsetsize
```

* Identifies **resource-hogging processes**.

#### **Find Processes by User**

```basic
wmic process where (caption="chrome.exe") get processid,executablepath,commandline
```

* Helps track **suspicious user-launched processes**.

#### **Kill a Process by PID**

```bash
wmic process where processid="1234" delete
```

* Replace `1234` with the target PID.

***

#### **3. Security Use Cases**

#### **Detect Hidden Processes**

Compare `wmic` with Task Manager:

```bash
wmic process list brief | findstr /i "suspicious_process"
```

* Uncovers **processes hidden by rootkits**.

#### **Check Process Command Line**

```bash
wmic process get commandline
```

* Reveals **malicious arguments** (e.g., PowerShell encoded attacks).

#### **Monitor Child Processes**

```bash
wmic process where (name="svchost.exe") get processid,parentprocessid
```

* Detects **process injection** (e.g., malware spawning from `svchost`).

***

#### **4. WMIC vs. Modern Alternatives**

| **Feature**      | **WMIC**                   | **PowerShell (Get-Process)**   |
| ---------------- | -------------------------- | ------------------------------ |
| **Process List** | `wmic process list brief`  | `Get-Process`                  |
| **Filtering**    | `where` clauses (SQL-like) | `Where-Object`                 |
| **User Context** | `wmic process get csname`  | `Get-Process -IncludeUserName` |
| **Kill Process** | `wmic process delete`      | `Stop-Process -Id 1234`        |
| **Deprecation**  | ❌ Discontinued in Win11    | ✅ Recommended for new systems  |

***

#### **5. Practical Example: Hunting Malware**

#### **Step 1: List Processes**

```bash
wmic process list brief | findstr /i "powershell"
```

* Checks for **suspicious PowerShell instances**.

#### **Step 2: Analyze Command Line**

```bash
wmic process where name="powershell.exe" get commandline
```

* Looks for **obfuscated scripts** (e.g., `-EncodedCommand`).

#### **Step 3: Kill Malicious Process**

```bash
wmic process where processid="5678" delete
```

* Terminates the threat.

***

#### **6. Limitations & Warnings**

* ❌ **No longer updated** (use PowerShell for Win10/11).
* ❌ **Limited real-time monitoring** (tools like **Sysinternals Process Explorer** are better).
* ⚠️ **Admin rights required** for full process control.

***

#### **Summary**

WMIC provides **fast process analysis** for legacy Windows systems, but **PowerShell (`Get-Process`)** is the modern replacement. Key uses:

1. **List/Kill processes**
2. **Detect malware hiding in legit processes**
3. **Analyze command-line arguments**

### <mark style="color:blue;">**2- Examining Network Usage with**</mark><mark style="color:blue;">**&#x20;**</mark><mark style="color:blue;">**`netstat`**</mark>&#x20;

#### **Examining Network Usage with `netstat -na`**

`netstat -na` is a fundamental Windows/Linux command for analyzing **active network connections and listening ports**. Below is a detailed breakdown of its usage, interpretation, and security applications.

***

#### **1. Basic Command & Output**

```bash
netstat -na
```

* **`-n`**: Shows addresses/ports in **numeric form** (no DNS resolution).
* **`-a`**: Displays **all** connections (including listening ports).

#### **Sample Output**

```
Proto  Local Address          Foreign Address        State
TCP    0.0.0.0:80            0.0.0.0:0              LISTENING
TCP    192.168.1.5:5353       8.8.8.8:443            ESTABLISHED
UDP    0.0.0.0:53            *:*                    LISTENING
```

***

#### **2. Key Columns Explained**

| **Column**          | **Meaning**                                                               |
| ------------------- | ------------------------------------------------------------------------- |
| **Proto**           | Protocol (`TCP`/`UDP`)                                                    |
| **Local Address**   | IP & port of the local machine (`0.0.0.0` = all interfaces)               |
| **Foreign Address** | Remote IP & port (`0.0.0.0:0` = no active connection)                     |
| **State**           | Connection status (`LISTENING`, `ESTABLISHED`, `CLOSE_WAIT`, `TIME_WAIT`) |

***

#### **3. Security Use Cases**

#### **A. Detect Unauthorized Listening Ports**

```bash
netstat -na | findstr /i "listening"
```

* Identifies **open ports** that could indicate:
  * **Malware backdoors** (e.g., `:4444` for Metasploit).
  * **Rogue services** (e.g., unexpected `:3389` for RDP).

#### **B. Check for Established Connections**

```bash
netstat -na | findstr /i "established"
```

* Reveals **active connections** to:
  * **Suspicious IPs** (e.g., foreign countries).
  * **Unknown services** (e.g., `:6667` for IRC bots).

#### **C. Find Hidden UDP Services**

```bash
netstat -na | findstr /i "udp"
```

* UDP is stateless but used for:
  * **DNS hijacking** (`:53`).
  * **Covert channels** (malware exfiltrating data).

#### **D. Identify Process Behind a Port**

```bash
netstat -nao | findstr ":80"
```

* **`-o`** adds **PID** (Process ID), which you can cross-check with:

  ```bash
  tasklist | findstr "1234"
  ```

***

#### **4. Advanced Variations**

| **Command**     | **Purpose**                                                    |
| --------------- | -------------------------------------------------------------- |
| `netstat -nab`  | Shows **process names** (requires Admin rights).               |
| `netstat -na 5` | Refreshes every **5 seconds** (monitor real-time changes).     |
| \`netstat -na   | findstr ":443"\`                                               |
| `netstat -s`    | Displays **statistics** (e.g., packets sent/received, errors). |

***

#### **5. Common Threat Indicators**

| **Observation**           | **Possible Threat**                  |
| ------------------------- | ------------------------------------ |
| `:4444` (TCP)             | **Metasploit reverse shell**.        |
| `:3389` (ESTABLISHED)     | **Unauthorized RDP access**.         |
| `:53` (UDP, unexpected)   | **DNS tunneling/data exfiltration**. |
| `:6667` (TCP)             | **IRC botnet communication**.        |
| Random high port (>30000) | **Malware C2 (Command & Control)**.  |

***

#### **6. Limitations & Better Alternatives**

* ❌ **No process details** (use `-b` or `-o` + `tasklist`).
* ❌ **No historical data** (tools like **Wireshark** or **TCPView** are better).
* ✅ **Best for quick checks** (combine with `tasklist` and `WMIC`).

***

#### **7. Example: Malware Investigation**

#### **Step 1: Check Suspicious Ports**

```bash
netstat -nao | findstr ":8080"
```

* If `8080` is open but unused, it may be a **backdoor**.

#### **Step 2: Find the Malicious Process**

```cmd
tasklist | findstr "5678"
```

* (Where `5678` is the PID from `netstat -nao`).

#### **Step 3: Kill the Process**

```bash
taskkill /PID 5678 /F
```

***

#### **8. Summary**

* **`netstat -na`** = Quick network snapshot.
* **Key Uses**:
  * Detect **malicious listening ports**.
  * Identify **unauthorized connections**.
  * Troubleshoot **network issues**.
* **For deeper analysis**, use:
  * **`netstat -nab`** (process names).
  * **TCPView** (GUI alternative).
  * **Wireshark** (packet-level inspection).

### <mark style="color:blue;">3- Examining Services (services.msc , sc query )</mark>

#### **Examining Services in Windows: `services.msc` vs. `sc query`**

Windows services are background processes that run automatically or manually. You can inspect them using:

* **GUI:** `services.msc` (Service Manager)
* **CLI:** `sc query` (Service Control command-line tool)

***

#### <mark style="color:green;">**1. Using**</mark><mark style="color:green;">**&#x20;**</mark><mark style="color:green;">**`services.msc`**</mark><mark style="color:green;">**&#x20;**</mark><mark style="color:green;">**(Graphical Interface)**</mark>

#### **How to Open:**

* Press `Win + R`, type `services.msc`, and hit **Enter**.
* Alternatively, search for **"Services"** in the Start menu.

#### **Key Features:**

| **Column**       | **Purpose**                                                               |
| ---------------- | ------------------------------------------------------------------------- |
| **Name**         | Service display name (e.g., "Windows Update").                            |
| **Description**  | Brief info about the service.                                             |
| **Status**       | `Running`, `Stopped`, or `Paused`.                                        |
| **Startup Type** | `Automatic`, `Manual`, `Disabled`, or `Delayed Start`.                    |
| **Log On As**    | Which account runs the service (`Local System`, `Network Service`, etc.). |

#### **Common Actions:**

* **Start/Stop/Restart** a service → Right-click → Select action.
* **Change Startup Type** → Right-click → **Properties** → Adjust **Startup type**.
* **Check Dependencies** → Properties → **Dependencies** tab.

#### **Use Cases:**

* **Disable unnecessary services** (e.g., `Bluetooth Support` if unused).
* **Check if malware is running as a service** (e.g., suspicious names like `UpdateHelper`).
* **Troubleshoot service crashes** (check **Event Viewer** logs).

***

#### <mark style="color:green;">**2. Using**</mark><mark style="color:green;">**&#x20;**</mark><mark style="color:green;">**`sc query`**</mark><mark style="color:green;">**&#x20;**</mark><mark style="color:green;">**(Command Line)**</mark>

#### **Basic Command:**

```bash
sc query
```

* Lists **all services** with their **state** (`RUNNING`/`STOPPED`).

#### **Filter Specific Service:**

```bash
sc query "wuauserv"
```

(Checks the **Windows Update** service.)

#### **Detailed Service Info:**

```bash
sc qc "wuauserv"
```

* Shows **binary path**, **start type**, and **dependencies**.

#### **Check Service Dependencies:**

```bash
sc enumdepend "wuauserv" 50
```

(Lists services that depend on Windows Update.)

#### **Start/Stop a Service:**

```bash
sc start "wuauserv"
sc stop "wuauserv"
```

#### **Change Startup Type:**

```powershell
sc config "wuauserv" start= disabled
```

(Options: `auto`, `demand`, `disabled`, `delayed-auto`.)

***

#### **3. Security & Malware Hunting**

#### **A. Detect Malicious Services**

1. **Check Suspicious Service Names:**

   ```powershell
   sc query | findstr /i "update helper"
   ```

   (Malware often uses names mimicking legit services.)
2. **Verify Binary Paths:**

   ```bash
   sc qc "suspicious_service" | findstr "BINARY_PATH_NAME"
   ```

   * If path is `C:\Temp\malware.exe`, it’s likely malicious.
3. **Compare with `services.msc`:**
   * Some rootkits hide services in GUI but not in `sc query`.

#### **B. Disable Malicious Services**

```bash
sc stop "malware_service"
sc config "malware_service" start= disabled
```

#### **C. Check Hidden Services (Advanced)**

```bash
sc query type= driver
```

(Some malware installs **kernel drivers** as services.)

***

#### **4.&#x20;**<mark style="color:red;">**`services.msc`**</mark><mark style="color:red;">**&#x20;**</mark><mark style="color:red;">**vs.**</mark><mark style="color:red;">**&#x20;**</mark><mark style="color:red;">**`sc query`**</mark><mark style="color:red;">**&#x20;**</mark><mark style="color:red;">**Comparison**</mark>

| **Feature**           | **`services.msc`**                 | **`sc query`**                           |
| --------------------- | ---------------------------------- | ---------------------------------------- |
| **Ease of Use**       | ✅ User-friendly GUI                | ❌ Requires command-line knowledge        |
| **Automation**        | ❌ Manual only                      | ✅ Scriptable (batch/PowerShell)          |
| **Detailed Info**     | ✅ Dependencies, description        | ✅ Binary path, PID, exact state          |
| **Hidden Services**   | ❌ May miss rootkit-hidden services | ✅ Can detect some hidden services        |
| **Remote Management** | ❌ Limited                          | ✅ Supports remote PCs (`sc \\PC1 query`) |

***

#### **5. Best Practices**

1. **Regularly Audit Services**
   * Disable unnecessary ones (e.g., `Telnet`, `Remote Registry`).
2. **Check for Unknown Services**
   * Cross-reference with `tasklist /svc` for process associations.
3. **Log Service Changes**
   * Use **Event Viewer** (`Windows Logs → System`) for service start/stop events.
4. **Use Sysinternals Tools**
   * **`Autoruns`** (checks all auto-start services).
   * **`Process Explorer`** (verifies service binaries).

***

#### **6. Example: Investigating a Suspicious Service**

#### **Step 1: Find the Service**

```bash
sc query | findstr /i "backdoor"
```

(If a service named `BackdoorSvc` appears.)

#### **Step 2: Check Its Executable**

```bash
sc qc "BackdoorSvc" | findstr "BINARY_PATH_NAME"
```

(If path is `C:\Malware\bd.exe`, it’s malicious.)

#### **Step 3: Disable & Delete**

```bash
sc stop "BackdoorSvc"
sc config "BackdoorSvc" start= disabled
del /f "C:\Malware\bd.exe"
```

***

#### **7. Summary**

* **`services.msc`** → Best for **manual inspection**.
* **`sc query`** → Best for **scripting/automation** and **malware hunting**.
* **Critical for:**
  * Disabling vulnerable services.
  * Detecting malware persistence.
  * Troubleshooting system issues.

### <mark style="color:blue;">4- Examining Registry (</mark><mark style="color:blue;">**Persistence Techniques)**</mark>

#### **Examining Autostart Extensibility Points (ASEPs) in Windows**

Autostart Extensibility Points (ASEPs) are registry keys, scheduled tasks, services, and file locations that allow programs to **automatically execute at system startup, user login, or other triggers**. Malware often abuses these for persistence.

***

#### <mark style="color:green;">**1. Common ASEP Locations**</mark>

**A. Registry-Based ASEPs**

**1. User-Level Autostart (Current User)**

* **`HKCU\Software\Microsoft\Windows\CurrentVersion\Run`**
  * Programs that launch at user login.
* **`HKCU\Software\Microsoft\Windows\CurrentVersion\RunOnce`**
  * Runs once at next login, then deletes itself (common in malware).

**2. System-Level Autostart (All Users)local-machine**

* **`HKLM\Software\Microsoft\Windows\CurrentVersion\Run`**
  * Runs for all users.
* **`HKLM\Software\Microsoft\Windows\CurrentVersion\RunOnce`**
  * Runs once at next boot (used by installers/cleanup tools).

**3. Other Key Registry ASEPs**

* **`HKLM\Software\Microsoft\Windows NT\CurrentVersion\Winlogon\Userinit`**
  * Default: `userinit.exe` (malware may append malicious EXEs).
* **`HKLM\Software\Microsoft\Windows NT\CurrentVersion\Winlogon\Shell`**
  * Should be `explorer.exe` (if modified, possible malware).
* **`HKLM\Software\Microsoft\Active Setup\Installed Components`**
  * Runs once per user (malware may inject commands).

***

#### **B. File System ASEPs**

**1. Startup Folders**

* **Current User:**\
  `%AppData%\Microsoft\Windows\Start Menu\Programs\Startup`
* **All Users:**\
  `%ProgramData%\Microsoft\Windows\Start Menu\Programs\Startup`

**2. Scheduled Tasks**

* Check via:

  ```cmd
  schtasks /query /fo LIST /v
  ```

  * Look for **suspicious tasks** (e.g., `UpdateChecker` running at logon).

**3. Services**

* **Legitimate services** (`services.msc` or `sc query`).
* **Malware** may install itself as a service.

**4. Browser Extensions & Helper Objects**

* **Edge/Chrome:**\
  `%LocalAppData%\Google\Chrome\User Data\Default\Extensions`
* **Internet Explorer:**\
  `HKLM\Software\Microsoft\Windows\CurrentVersion\Explorer\Browser Helper Objects`

***

#### <mark style="color:green;">**2. How to Examine ASEPs**</mark>

#### **A. Using Registry Editor (`regedit`)**

1. Press `Win + R`, type `regedit`, and navigate to ASEP keys.
2. Look for:
   * **Unknown executables** (e.g., `C:\Temp\malware.exe`).
   * **Suspicious modifications** (e.g., `explorer.exe` replaced with `evil.exe`).

#### **B. Using Command Line**

**1. List All Run Keys**

```bash
reg query "HKCU\Software\Microsoft\Windows\CurrentVersion\Run"
reg query "HKLM\Software\Microsoft\Windows\CurrentVersion\Run"
```

**2. Check Scheduled Tasks**

```bash
schtasks /query /fo TABLE /v
```

**3. Check Services**

```bash
sc query | findstr "SERVICE_NAME"
```

**4. Check Startup Folders**

```bash
dir "%AppData%\Microsoft\Windows\Start Menu\Programs\Startup"
dir "%ProgramData%\Microsoft\Windows\Start Menu\Programs\Startup"
```

***

#### <mark style="color:green;">**3. Malware Persistence Techniques**</mark>

| **Technique**            | **Example**                                     | **Detection Method**      |
| ------------------------ | ----------------------------------------------- | ------------------------- |
| **Registry Run Keys**    | `HKCU\...\Run\evil.exe`                         | `reg query`               |
| **Scheduled Tasks**      | `schtasks /create /tn "Update" /tr malware.exe` | `schtasks /query`         |
| **Service Installation** | `sc create MalwareService binpath= C:\evil.exe` | `sc query`                |
| **Startup Folder**       | `%Startup%\backdoor.lnk`                        | Manual folder check       |
| **DLL Hijacking**        | Replace `legit.dll` with malicious one          | `Autoruns` (Sysinternals) |

***

#### <mark style="color:green;">**4. Tools for ASEP Analysis**</mark>

#### **A. Sysinternals Autoruns**

* **Best tool** for comprehensive ASEP checks.
* Download: <https://learn.microsoft.com/en-us/sysinternals/downloads/autoruns>
* Usage:

  ```bash
  Autoruns.exe
  ```

  * Checks **all ASEPs** (registry, tasks, services, DLLs).

#### **B. PowerShell (Get Scheduled Tasks)**

```powershell
Get-ScheduledTask | Where-Object { $_.State -ne "Disabled" } | Select-Object TaskName, Actions
```

#### **C. WMIC (Check Services)**

```bash
wmic service get name,pathname,startmode | findstr /i "auto"
```

***

#### <mark style="color:green;">**5. Example: Hunting Malware Persistence**</mark>

**Step 1: Check Suspicious Run Keys**

```bash
reg query "HKLM\Software\Microsoft\Windows\CurrentVersion\Run" /s
```

* If `C:\Temp\bad.exe` is found, investigate.

#### **Step 2: Verify Scheduled Tasks**

```bash
schtasks /query /fo LIST | findstr "malware"
```

#### **Step 3: Check Services**

```bash
sc query | findstr "UnknownService"
```

#### **Step 4: Delete Malicious Entry**

```bash
reg delete "HKLM\Software\Microsoft\Windows\CurrentVersion\Run" /v "BadProgram" /f
```

***

#### <mark style="color:green;">**6. Summary**</mark>

* **ASEPs** = Critical persistence mechanisms for **both legitimate apps & malware**.
* **Check:**
  * **Registry Run keys** (`HKCU\Run`, `HKLM\Run`).
  * **Startup folders** (`%AppData%\Startup`).
  * **Scheduled tasks** (`schtasks /query`).
  * **Services** (`sc query`).
* **Best Tools:**
  * **`Autoruns`** (Sysinternals).
  * **`reg query`** (manual checks).
  * **`schtasks`** (task scheduler).

### <mark style="color:blue;">**5- Detecting & Analyzing Unusual Log Entries in Windows**</mark>

Unusual log entries can indicate **security breaches, system failures, or malware activity**. Windows logs events in the **Event Viewer**, but manual analysis is tedious. Below are key methods to identify suspicious entries.

***

#### <mark style="color:green;">**1. Critical Windows Logs to Monitor**</mark>

| **Log Name**                                 | **Location**                                                           | **Relevance**                                                                      |
| -------------------------------------------- | ---------------------------------------------------------------------- | ---------------------------------------------------------------------------------- |
| **Security**                                 | `Event Viewer → Windows Logs → Security`                               | Tracks **logins, privilege changes, audit failures** (Brute Force, Pass-the-Hash). |
| **System**                                   | `Event Viewer → Windows Logs → System`                                 | Records **service crashes, driver errors, unexpected shutdowns**.                  |
| **Application**                              | `Event Viewer → Windows Logs → Application`                            | Logs **app errors, crashes, suspicious installs** (e.g., malware droppers).        |
| **Microsoft-Windows-PowerShell/Operational** | `Applications and Services Logs → Microsoft → Windows → PowerShell`    | Captures **malicious PowerShell execution** (e.g., encoded commands).              |
| **Task Scheduler**                           | `Applications and Services Logs → Microsoft → Windows → TaskScheduler` | Detects **malicious scheduled tasks**.                                             |

***

#### <mark style="color:green;">**2. Common Unusual Log Patterns**</mark>

#### **A. Security Log Red Flags**

| **Event ID** | **Description**                   | **Potential Threat**                                     |
| ------------ | --------------------------------- | -------------------------------------------------------- |
| **4625**     | Failed login (Brute Force Attack) | RDP/SSH brute-forcing.                                   |
| **4672**     | Admin privilege assignment        | Unexpected admin rights (Privilege Escalation).          |
| **4688**     | New process creation              | Malware execution (`cmd.exe` spawning `powershell.exe`). |
| **4698**     | Scheduled task creation           | Malware persistence.                                     |
| **1102**     | Log cleared                       | Attacker covering tracks.                                |

#### **B. System/Application Log Red Flags**

| **Event ID** | **Description**              | **Potential Threat**                      |
| ------------ | ---------------------------- | ----------------------------------------- |
| **7034**     | Service crashed unexpectedly | Malware tampering with services.          |
| **1000**     | Application crash            | Exploit attempts (e.g., buffer overflow). |
| **7045**     | New service installed        | Malware registering as a service.         |

#### **C. PowerShell Log Red Flags**

| **Event ID** | **Description**      | **Potential Threat**           |
| ------------ | -------------------- | ------------------------------ |
| **4104**     | Script block logging | Obfuscated PowerShell malware. |
| **4103**     | Module logging       | Suspicious modules loading.    |

## <mark style="color:orange;">Powershell vs legcy commands</mark>

| Legacy Command       | PowerShell Cmdlet      | Purpose                   |
| -------------------- | ---------------------- | ------------------------- |
| `wmic.exe process`   | `Get-Process`          | List running processes    |
| `netstat.exe -nao`   | `Get-NetTCPConnection` | View network connections  |
| `sc.exe query`       | `Get-Service`          | List system services      |
| `reg.exe`            | `Get-ChildItem`        | Access registry data      |
| `net.exe user`       | `Get-LocalUser`        | List local user accounts  |
| `net.exe localgroup` | `Get-LocalGroup`       | List local groups         |
| `schtasks.exe`       | `Get-ScheduledTask`    | List scheduled tasks      |
| `wevtutil.exe`       | `Get-WinEvent`         | Access Windows Event Logs |
| `fc.exe`             | `Compare-Object`       | Compare files/objects     |

***

#### <mark style="color:blue;">**1. List Running Processes**</mark>

**Legacy (WMIC):**

```cmd
wmic.exe process get Name,ProcessId,CommandLine
```

* Lists processes with name, PID, and command-line arguments.
* Output is unstructured (plain text).

**PowerShell:**

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

* Structured object output (can be filtered, sorted, or exported).
* Example with filtering:

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

***

#### <mark style="color:blue;">**2. Check Network Connections**</mark>

**Legacy (netstat):**

```cmd
netstat.exe -nao
```

* Displays active connections with ports and owning process IDs.
* Hard to filter (text-based).

**PowerShell:**

```powershell
Get-NetTCPConnection | Select-Object LocalAddress, LocalPort, RemoteAddress, State, OwningProcess
```

* Filterable output (e.g., find only `ESTABLISHED` connections):

  ```powershell
  Get-NetTCPConnection | Where-Object { $_.State -eq "Established" }
  ```

***

#### <mark style="color:blue;">**3. List Services**</mark>

**Legacy (sc):**

```cmd
sc.exe query
```

* Lists services but with limited formatting.

**PowerShell:**

```powershell
Get-Service | Select-Object Name, Status, DisplayName
```

* Filter running services:

  ```powershell
  Get-Service | Where-Object { $_.Status -eq "Running" }
  ```

***

#### <mark style="color:blue;">**4. Registry Access**</mark>

**Legacy (reg):**

```cmd
reg.exe query "HKLM\Software\Microsoft\Windows\CurrentVersion"
```

* Text-based output.

**PowerShell:**

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

* Structured output (can export to CSV/JSON).

***

#### <mark style="color:blue;">**5. List Local Users**</mark>

**Legacy (net user):**

```cmd
net.exe user
```

* Lists users in plain text.

**PowerShell:**

```powershell
Get-LocalUser | Select-Object Name, Enabled, LastLogon
```

* More details and filterable:

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

***

#### <mark style="color:blue;">**6. List Local Groups**</mark>

**Legacy (net localgroup):**

```cmd
net.exe localgroup
```

* Basic group listing.

**PowerShell:**

```powershell
Get-LocalGroup | Select-Object Name, Description
```

* Get group members:

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

***

#### <mark style="color:blue;">**7. Scheduled Tasks**</mark>

**Legacy (schtasks):**

```cmd
schtasks.exe /query /fo LIST
```

* Lists tasks in text format.

**PowerShell:**

```powershell
Get-ScheduledTask | Select-Object TaskName, State, TaskPath
```

* Filter enabled tasks:

  ```powershell
  Get-ScheduledTask | Where-Object { $_.State -ne "Disabled" }
  ```

***

#### <mark style="color:blue;">**8. Event Logs**</mark>

**Legacy (wevtutil):**

```cmd
wevtutil.exe qe System /c:5
```

* Queries the last 5 System logs (hard to parse).

**PowerShell:**

```powershell
Get-WinEvent -LogName System -MaxEvents 5 | Select-Object TimeCreated, Message
```

* Filter by date/event ID:

  ```powershell
  Get-WinEvent -FilterHashtable @{LogName="System"; ID=6005,6006} 
  ```

***

#### <mark style="color:blue;">**9. File Comparison**</mark>

**Legacy (fc):**

```cmd
fc.exe file1.txt file2.txt
```

* Shows differences in text files.

**PowerShell:**

```powershell
Compare-Object (Get-Content file1.txt) (Get-Content file2.txt)
```

* More readable output (shows which lines differ).

***

#### <mark style="color:blue;">**Key Takeaways:**</mark>

| **Aspect**        | **Legacy Commands** | **PowerShell**                             |
| ----------------- | ------------------- | ------------------------------------------ |
| **Output Format** | Text-based          | Structured objects                         |
| **Filtering**     | Limited (manual)    | Built-in (`Where-Object`, `Select-Object`) |
| **Extensibility** | Hard to automate    | Easily scriptable                          |
| **Readability**   | Less intuitive      | More human-friendly                        |

#### <mark style="color:blue;">**When to Use Which?**</mark>

✔ **Use Legacy Commands** if:

* You need quick, one-off checks.
* You're more familiar with CMD syntax.

✔ **Use PowerShell** if:

* You need structured data (e.g., filtering, exporting).
* You're automating tasks or scripting.

## <mark style="color:orange;">Network Investigations ?</mark>

#### **Network Investigations: Sources, Accessibility, Fidelity & Challenges**

Network investigations involve analyzing traffic, devices, and logs to detect threats, troubleshoot issues, or gather forensic evidence. Below is a structured breakdown of **sources of evidence**, **data accessibility issues**, **fidelity concerns**, and **key challenges** in network forensics.

***

#### <mark style="color:blue;">**1. Sources of Evidence in Network Investigations**</mark>

| **Source**          | **Examples**                                     | **Use Cases**                                      |
| ------------------- | ------------------------------------------------ | -------------------------------------------------- |
| **Network Traffic** | PCAP files (`tcpdump`, Wireshark), NetFlow/sFlow | Detect malware C2, data exfiltration, DDoS attacks |
| **Network Devices** | Firewalls, IDS/IPS, Routers, Proxies             | Log allowed/blocked connections, detect intrusions |
| **Host Devices**    | Windows/Linux logs, memory dumps, process lists  | Identify compromised endpoints, lateral movement   |
| **Cloud/Edge**      | AWS VPC logs, IoT device telemetry               | Investigate cloud breaches, IoT attacks            |

***

#### <mark style="color:blue;">**2. Data Accessibility Challenges**</mark>

#### **A. Export & Collection Issues**

* **Problem**: Some devices restrict log exports (e.g., proprietary formats).
* **Example**:
  * Cisco ASA firewalls require `ASDM` or `CSV` conversions for full log analysis.
  * IoT devices may only stream data to vendor-specific clouds.

#### **B. Legal & Compliance Barriers**

* **GDPR/CLOUD Act**: Limits cross-border data sharing.
* **Solution**: Use tools like **Splunk**/**ELK** for centralized, compliant logging.

***

#### <mark style="color:blue;">**3. Fidelity Issues (Missing/Incomplete Data)**</mark>

| **Issue**              | **Impact**            | **Workaround**                              |
| ---------------------- | --------------------- | ------------------------------------------- |
| **Packet Loss**        | Gaps in PCAPs         | Use `tcpreplay` to test detection coverage. |
| **Log Rotation**       | Old logs deleted      | Configure longer retention policies.        |
| **Edge Device Limits** | IoT devices drop logs | Forward logs to a SIEM in real-time.        |

***

### <mark style="color:blue;">**4. Visibility Challenges (Encryption & Evasion)**</mark>

#### **A. Encryption (TLS/SSL)**

* **Problem**: Hides malicious traffic (e.g., C2 over HTTPS).
* **Solutions**:
  * **SSL Decryption**: Deploy proxies (e.g., Squid + SSL inspection).
  * **JA3 Fingerprinting**: Detect malware by TLS handshake patterns.

#### **B. Anti-Forensics Techniques**

| **Tactic**          | **Example**                     | **Detection**                             |
| ------------------- | ------------------------------- | ----------------------------------------- |
| **DNS Tunneling**   | Exfiltrate data via DNS queries | Monitor for long/lookup TXT records.      |
| **Time-Stomping**   | Modify file timestamps          | Check `MFT` (Windows) or `inode` (Linux). |
| **Covert Channels** | ICMP/data in packet headers     | Analyze payloads with `Wireshark`.        |

### <mark style="color:blue;">Tcpdump</mark>

**tcpdump** is a powerful command-line packet analyzer tool used to capture and display network traffic in real-time. It allows you to inspect TCP/IP and other packets being transmitted or received over a network.

Here’s a **cleaner, more structured breakdown** of the most useful `tcpdump` options with practical examples:

***

#### **1. Basic Capture**

**Capture live traffic on an interface**

```sh
tcpdump -i eth0          # Listen on eth0
tcpdump -i any           # Listen on ALL interfaces
tcpdump -D               # List available interfaces
```

* **Why?** Debug local network issues, monitor traffic.

***

#### **2. Save to File & Read Later**

**Write packets to a file (PCAP format)**

```sh
tcpdump -i eth0 -w capture.pcap   # Save raw packets
```

* **Why?** Analyze later in Wireshark or other tools.

**Read from a saved PCAP file**

```sh
tcpdump -r capture.pcap           # Read file
tcpdump -nnr capture.pcap         # Disable DNS/port resolution
tcpdump -Ar capture.pcap          # Show ASCII content (e.g., HTTP)
```

* **Why?** Inspect historical traffic without recapturing.

***

#### **3. Filtering Traffic**

**Filter by host, port, or protocol**

```sh
tcpdump host 192.168.1.100        # Traffic to/from IP
tcpdump src 10.0.0.5              # Only from source IP
tcpdump dst 8.8.8.8               # Only to destination IP
tcpdump port 80                   # HTTP traffic
tcpdump tcp port 22               # SSH traffic
tcpdump icmp                      # Ping/ICMP packets
```

* **Why?** Narrow down to specific traffic (e.g., malware analysis).

***

#### **4. Output Formats**

**Human-readable output**

```sh
tcpdump -A                        # ASCII (text protocols)
tcpdump -X                        # Hex + ASCII (binary protocols)
tcpdump -v                        # Verbose (more details)
tcpdump -vvv                      # Maximum verbosity
```

* **Why?** Debug HTTP, SMTP, or binary protocols like DNS.

***

#### **5. Practical Examples**

**Capture 50 HTTPS packets and save**

```sh
tcpdump -i eth0 -c 50 -w https.pcap port 443
```

**Capture traffic between two hosts**

```sh
tcpdump -i eth0 host 192.168.1.1 and host 192.168.1.2
```

***

#### **Key Notes**

* **Run as root**: Use `sudo` or run as root for full access.
* **Stop capture**: Press `Ctrl+C`.
* **Limit size**: Use `-c 100` to avoid huge files.
* **BPF filters**: Advanced filtering (e.g., `tcp[tcpflags] & (tcp-syn) != 0` for SYN packets).

***

#### **Cheat Sheet Table**

| **Command**                               | **Action**                |
| ----------------------------------------- | ------------------------- |
| `tcpdump -i eth0 -n`                      | Basic capture (IPs only)  |
| `tcpdump -i any -w file.pcap`             | Save all traffic to file  |
| `tcpdump -r file.pcap -nn -A`             | Read file + show ASCII    |
| `tcpdump port 53`                         | DNS traffic               |
| `tcpdump src 192.168.1.1 and dst port 80` | HTTP from specific source |

***

### <mark style="color:blue;">Berkeley Packet Filters (BPF)</mark>

**BPF (Berkeley Packet Filter)** is a low-level mechanism for **filtering network packets** efficiently before they reach user-space applications like `tcpdump`, Wireshark, or firewall tools. It allows you to capture **only the traffic you need**, reducing CPU and memory overhead.

***

#### **1. How BPF Works**

* BPF runs in the **kernel**, filtering packets **before** they are copied to user space.
* It uses a **virtual machine** with its own instruction set to evaluate filters quickly.
* Tools like `tcpdump` compile filter expressions (e.g., `port 80`) into **BPF bytecode**, which the kernel executes.

***

#### **2. BPF Syntax Basics**

BPF filters consist of **primitives** that match packet fields:

| **Primitive**      | **Meaning**                      | **Example**                      |
| ------------------ | -------------------------------- | -------------------------------- |
| `dst host`         | Destination IP                   | `dst host 8.8.8.8`               |
| `src host`         | Source IP                        | `src host 192.168.1.1`           |
| `port`             | Port number (TCP/UDP)            | `port 443`                       |
| `proto`            | Protocol (TCP, UDP, ICMP, etc.)  | `proto TCP`                      |
| `net`              | Network (CIDR notation)          | `net 192.168.1.0/24`             |
| `less` / `greater` | Packet size                      | `less 100` (captures <100 bytes) |
| `tcpflags`         | Match TCP flags (SYN, ACK, etc.) | `tcp[tcpflags] & tcp-syn != 0`   |

***

#### **3. Common BPF Filters in `tcpdump`**

#### **Basic Filters**

| **Filter**                     | **What It Does**                   |
| ------------------------------ | ---------------------------------- |
| `tcpdump 'port 80'`            | Captures HTTP traffic              |
| `tcpdump 'host 1.1.1.1'`       | Captures traffic to/from `1.1.1.1` |
| `tcpdump 'net 192.168.1.0/24'` | Captures traffic in a subnet       |

#### **Advanced Filters**

| **Filter**                               | **What It Does**                               |
| ---------------------------------------- | ---------------------------------------------- |
| `tcpdump 'tcp[13] & 2 != 0'`             | Captures **TCP SYN packets** (new connections) |
| `tcpdump 'icmp[0] == 8'`                 | Captures **ICMP Echo Requests (ping)**         |
| `tcpdump 'udp and port 53'`              | Captures **DNS queries**                       |
| `tcpdump 'ether host 00:11:22:33:44:55'` | Captures traffic by **MAC address**            |

***

#### **4. BPF in `tcpdump` vs. Wireshark**

| **Feature**       | **`tcpdump` BPF**         | **Wireshark (Display Filters)** |
| ----------------- | ------------------------- | ------------------------------- |
| **Syntax**        | `port 80`                 | `tcp.port == 80`                |
| **Layer 2 (MAC)** | `ether host xx`           | `eth.addr == xx`                |
| **IP Fragments**  | `ip[6:2] & 0x1fff != 0`   | `ip.flags.mf == 1`              |
| **Performance**   | **Faster** (kernel-level) | Slower (post-capture)           |

***

#### **5. Why BPF Matters**

* **Efficiency**: Reduces CPU/memory usage by filtering early.
* **Precision**: Captures only relevant traffic (e.g., `SYN` scans in security monitoring).
* **Flexibility**: Supports complex bit-level filtering (e.g., `tcp[13]` for TCP flags).

***

#### **Summary**

* **BPF = Kernel-level packet filtering** (faster than user-space tools).
* **Used in `tcpdump`, `libpcap`, firewalls, and eBPF (extended BPF)**.
* **Allows bit-level packet inspection** (e.g., TCP flags, custom hex matching).

### <mark style="color:blue;">Web Proxies</mark>

**1. Purpose of Web Proxies in Corporate Environments**

* **Bandwidth Optimization**:\
  Proxies cache frequently accessed web content (e.g., images, videos), reducing external bandwidth usage.\
  **Example**: If 100 employees visit the same news site, the proxy serves the cached version instead of downloading it 100 times.
* **Content Filtering**:\
  Block access to inappropriate or non-work-related sites (e.g., social media, malware domains).\
  **Example**: A proxy can enforce company policies by denying requests to `netflix.com`.
* **Security & Compliance**:\
  Log all web traffic to monitor employee activity and prevent data leaks.

***

**2. Role in Digital Investigations**

* **User Profiling**:\
  Proxies record **full URLs, timestamps, and user identities**, helping investigators:
  * Track which employees accessed sensitive data.
  * Detect insider threats (e.g., exfiltrating files via cloud storage).
* **Anomaly Detection**:\
  Identify suspicious patterns like:
  * Repeated access to phishing sites.
  * Unusual data uploads (e.g., to `pastebin.com`).
* **SSL/TLS Interception**:\
  Some proxies decrypt HTTPS traffic (via **MITM**) to inspect encrypted threats.\
  **Controversy**: Raises privacy concerns but is critical for threat detection.

***

**3. Popular Web Proxy Tools**

| **Proxy**                                           | **Type**    | **Key Feature**                             |
| --------------------------------------------------- | ----------- | ------------------------------------------- |
| <mark style="color:green;">**Squid**</mark>         | Open-source | Caching, ACL-based filtering                |
| <mark style="color:green;">**Blue Coat**</mark>     | Enterprise  | Advanced threat protection (SSL inspection) |
| <mark style="color:green;">**Forefront TMG**</mark> | Microsoft   | Integrates with Active Directory            |

***

**4. Why Proxies Matter for Security Teams**

* **Visibility**: See all web traffic, even in encrypted (HTTPS) environments.
* **Control**: Enforce policies (e.g., block ransomware C2 servers).
* **Forensics**: Proxy logs are key evidence in breach investigations.

**Example Investigation**:\
An employee downloads malware. Proxy logs show:

* The exact time of download.
* The malicious URL.
* The user’s internal IP.

***

#### **Key Takeaways**

1. **Proxies save bandwidth** (caching) and **enforce policies** (filtering).
2. **Critical for investigations**—they log user activity and detect anomalies.
3. **SSL inspection** is powerful but ethically debated.
4. **Squid** is the go-to open-source option; enterprises use **Blue Coat** or **Microsoft TMG**.

**For IT Teams**: Configure proxies to balance **security, privacy, and performance**.\
**For Investigators**: Proxy logs are gold—correlate them with firewall/EDR data.

### <mark style="color:blue;">**Access Logs**</mark>&#x20;

**1. What Are Access Logs?**

Access logs are records generated by **web servers, proxies, and applications** that track every request made to them. They are crucial for:

* **Security monitoring** (detecting attacks like SQLi, XSS, or brute force).
* **Troubleshooting** (debugging broken pages or slow performance).
* **Compliance/auditing** (proving who accessed what and when).

***

**2. Typical Data Recorded**

While the **exact format varies**, most access logs include:

| **Field**       | **Example**                                      | **Purpose**                                                  |
| --------------- | ------------------------------------------------ | ------------------------------------------------------------ |
| **IP Address**  | `192.168.1.100`                                  | Identify the requester (attacker or user).                   |
| **Timestamp**   | `[10/Oct/2023:14:32:45 +0000]`                   | Track when an incident occurred.                             |
| **HTTP Method** | `GET /admin.php HTTP/1.1`                        | Detect suspicious actions (e.g., `POST` to sensitive pages). |
| **Status Code** | `200` (OK), `404` (Not Found), `403` (Forbidden) | Spot failed intrusion attempts.                              |
| **User-Agent**  | `Mozilla/5.0 (Windows NT 10.0; Win64; x64)`      | Identify automated tools (e.g., `sqlmap`, `nikto`).          |
| **Referrer**    | `https://google.com/search?q=login+page`         | See how users reached a vulnerable endpoint.                 |

**Note**: Some logs **exclude full URLs** (e.g., query strings like `?id=1' AND 1=1--`), limiting forensic value.

***

**3. Security Use Cases**

**Incident Detection**

* **Brute Force Attacks**:

  ```log
  192.168.1.50 - - [10/Oct/2023:14:33:12 +0000] "POST /wp-login.php HTTP/1.1" 200  
  192.168.1.50 - - [10/Oct/2023:14:33:13 +0000] "POST /wp-login.php HTTP/1.1" 200  
  ```

  → Rapid repeated `POST` requests to `/wp-login.php` suggest a password-guessing attack.
* **Directory Traversal**:

  ```log
  203.0.113.5 - - [10/Oct/2023:14:34:01 +0000] "GET /../../etc/passwd HTTP/1.1" 200  
  ```

  → Attempt to access sensitive system files.

**Post-Incident Forensics**

* Trace an attacker’s path:

  ```log
  94.130.12.7 - - [10/Oct/2023:14:35:00 +0000] "GET /backup.zip HTTP/1.1" 200  
  94.130.12.7 - - [10/Oct/2023:14:35:02 +0000] "GET /wp-admin/install.php HTTP/1.1" 200  
  ```

  → Indicates data theft (`backup.zip`) followed by a website takeover attempt.

***

**4. Log Customization**

* **Apache**: Modify `httpd.conf` or `.htaccess` with `LogFormat`.
* **Nginx**: Adjust `nginx.conf` with `log_format`.
* **Squid Proxy**: Configure `access_log` directives.

**Example (Apache)**:

```apache
LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined  
CustomLog /var/log/apache2/access.log combined  
```

***

**5. Limitations**

* **Privacy Concerns**: Logging full URLs may capture sensitive data (e.g., passwords in `?q=`).
* **Storage Overhead**: High-traffic sites generate massive logs (use log rotation tools like `logrotate`).
* **Evasion Tactics**: Attackers can spoof User-Agents or use proxies/Tor to hide their IP.

***

#### **Key Takeaways**

1. **Access logs are a goldmine** for detecting attacks and investigating breaches.
2. **Default logs may miss critical details** (e.g., query strings)—customize them.
3. **Look for patterns**: Repeated failures, unusual paths, or known malicious User-Agents.
4. **Correlate with other logs** (e.g., firewall, IDS) for full context.

**Pro Tip**: Use tools like **GoAccess**, **ELK Stack**, or **Splunk** to analyze large log files efficiently.

### <mark style="color:blue;">**Squid Proxy Access Logs**</mark>&#x20;

**1. Purpose & Key Features**

* Records every request passing through the **Squid proxy**.
* **Default format is verbose**, but customizable.
* Critical for **monitoring, troubleshooting, and security investigations**.

**2. Log Structure (Default Format)**

Each line contains these **10 fields**:

| **Field**          | **Description**                                                                                             |
| ------------------ | ----------------------------------------------------------------------------------------------------------- |
| **Timestamp**      | Unix epoch time (seconds since 1/1/1970 UTC) + milliseconds. Subtract `Duration` to get request start time. |
| **Duration**       | Milliseconds taken by the proxy to process the request.                                                     |
| **Client**         | IP address of the requesting client.                                                                        |
| **Result Codes**   | Squid result code + HTTP status code (e.g., `TCP_MISS/200`).                                                |
| **Size**           | Response size in bytes sent to the client.                                                                  |
| **HTTP Method**    | Request method (e.g., `GET`, `POST`).                                                                       |
| **URL**            | Requested URL (may be hidden for HTTPS unless interception is enabled).                                     |
| **User**           | Client identity (from auth/TLS/IDENT). Default: `-` (anonymous).                                            |
| **Hierarchy Code** | How the request was handled (e.g., `DIRECT` for no cache, `PARENT` for upstream proxy).                     |
| **Content Type**   | MIME type of the response (e.g., `text/html`).                                                              |

## <mark style="color:orange;">Memory Investigations</mark>

**1. Why Memory Forensics Matters**

* **RAM contains critical evidence** (processes, network connections, encryption keys) that isn’t stored on disk.
* **Preserves volatile data**—unlike live systems, a memory snapshot won’t change during analysis.

**2. Key Steps**

1. **Capture RAM**:
   * Use <mark style="color:blue;">**WinPmem**</mark> (Windows) to dump memory into a `.raw` file.
   * *Requires admin privileges*.
   * Example:

     ```powershell
     .\winpmem_mini.exe .\win10.0.22000.556.raw
     ```
2. **Analyze the Image**:
   * Tools like **Volatility** inspect the snapshot for:
     * **Malicious processes** (e.g., hidden malware).
     * **Network connections** (e.g., C2 servers).
     * **Artifacts** (e.g., encryption keys, injected code).

**3. Live vs. Memory Image Analysis**

* **Same goals** (find suspicious activity) but **different tools**.
* **Advantage of memory images**: Evidence is frozen, eliminating tampering risks.

**4. Pro Tips**

* **WinPmem is free/open-source**: [GitHub](https://github.com/Velocidex/WinPmem).
* **Correlate with disk forensics** for a complete investigation.

### <mark style="color:blue;">**Volatility**</mark>&#x20;

**1. Overview**

* **Purpose**: Open-source memory forensics tool for analyzing RAM dumps (e.g., from WinPmem).
* **Versions**:
  * **Volatility 2.x** (Legacy): Extensive plugin library but slower.
  * **Volatility 3.x** (2021+): Faster, modular, and Python 3-compatible, but some plugins not yet ported.

**2. Key Features**

* **Cross-Platform**: Runs on Windows, macOS, and Linux via Python.
* **Plugin-Based**: Modules follow a structured naming convention (e.g., `windows.pslist.PsList` for listing processes).
* **Flexible Input**: Supports multiple memory dump formats (e.g., `.raw`, `.mem`, hibernation files).

**3. Basic Usage**

```bash
volatility -f <memory_dump.raw> <plugin_name>  # Volatility 2  
python3 vol.py -f <memory_dump.raw> <plugin_name>  # Volatility 3  
```

**Example**:

```bash
python3 vol.py -f win10_memory.raw windows.pslist.PsList  
```

**4. Common Plugins**

| **Plugin**                  | **Function**                                |
| --------------------------- | ------------------------------------------- |
| `windows.pslist.PsList`     | List running processes.                     |
| `windows.netscan.NetScan`   | Detect network connections.                 |
| `windows.malfind.Malfind`   | Identify injected code/DLLs.                |
| `windows.registry.Registry` | Extract registry hives (e.g., SAM, SYSTEM). |
| `linux.bash.Bash`           | Recover command history (Linux).            |

**5. Version Considerations**

* **Volatility 2**: Use for legacy plugins (e.g., `yarascan` for malware signatures).
* **Volatility 3**: Preferred for performance and modern OS support (Windows 10/11, Linux 5.x).

**6. Resources**

* **Official Docs**: [Volatility Foundation](https://www.volatilityfoundation.org/)
* **GitHub**: [Volatility 3](https://github.com/volatilityfoundation/volatility3)

**7. Pro Tips**

* **Profile Selection**: Volatility 3 auto-detects OS profiles; Volatility 2 requires manual `--profile=Win10x64_19041`.
* **Combine with Disk Forensics**: Correlate RAM artifacts with disk evidence (e.g., prefetch files).

## <mark style="color:orange;">Malware Investigations</mark>

**1. Core Challenge: "Is This Malicious?"**

* **Suspicious ≠ Malicious**: Odd process names or behaviors (e.g., `svch0st.exe`) may be benign.
* **Indicators of Compromise (IOCs)**: Require validation—existing threat intel might not cover new/evolving malware.

**2. Two Investigation Approaches**

| **Approach**            | **Description**                                                         | **Tools**                                                                                     |
| ----------------------- | ----------------------------------------------------------------------- | --------------------------------------------------------------------------------------------- |
| **Behavioral Analysis** | Monitor malware’s **runtime actions** (files, registry, network calls). | <p>- Process Monitor (ProcMon)<br>- Wireshark<br>- Cuckoo Sandbox<br>- Sysinternals Suite</p> |
| **Static Analysis**     | Examine **code structure** (disassembly, strings, headers).             | <p>- Ghidra<br>- IDA Pro<br>- PEStudio<br>- Strings command</p>                               |

**3. Key Steps**

1. **Triage**:
   * Check file hashes (MD5/SHA-1) against VirusTotal.
   * Look for anomalous behavior (e.g., spawning `cmd.exe` unexpectedly).
2. **Dynamic Analysis**:
   * Run in a **sandbox** (e.g., Cuckoo) to log API calls, network traffic, and file changes.
3. **Static Analysis**:
   * Extract **strings** (e.g., `strings malware.exe | grep "http"`).
   * Reverse engineer with **Ghidra/IDA** to uncover C2 IPs or payload logic.
4. **Threat Intel Integration**:
   * Share IOCs (IPs, hashes, YARA rules) with teams/SIEMs.

**4. Pitfalls**

* **False Positives**: Legitimate software (e.g., backup tools) may behave "suspiciously."
* **Evasion Tactics**: Malware can detect sandboxes/VMs (e.g., checking for `vmware` processes).

**5. Pro Tips**

* **Combine Both Methods**: Behavioral analysis reveals *what* malware does; static analysis explains *how*.
* **Automate with YARA**: Write rules to detect malware families (e.g., `rule Emotet { strings: $a = "emotet" }`).
* **Document Everything**: Malware evolves—detailed notes help future investigations.

**Example Workflow**:

1. Find unknown `updatehelper.exe` running.
2. **Behavioral**: ProcMon shows it writing to `C:\Windows\Temp\payload.dll`.
3. **Static**: Ghidra reveals it connects to `185.63.90.1` (known C2 server).
4. **Conclusion**: Malware—block IP, hunt for other infections.

### <mark style="color:blue;">Threat Intel</mark>

#### **Online Malware Analysis Sites – Summary**

**1. Why Use Online Analysis Tools?**

* **Fast Triage**: Automatically scan files/URLs against multiple antivirus engines or sandboxes.
* **No Local Setup**: Avoid infecting your own systems—analysis happens in the cloud.
* **Threat Intel**: Compare results with historical malware data.

***

**2. Top Platforms & Their Uses**

| **Service**                                             | **Key Features**                                                                                                                                                                          | **Privacy Considerations**                                                                                                                                                                   |
| ------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| [**VirusTotal**](https://www.virustotal.com/)           | <p>- Scans files/URLs with <strong>70+ AV engines</strong> (e.g., Kaspersky, CrowdStrike).<br>- Provides hashes, behavior snippets, and community comments.</p>                           | <p>- Uploaded samples are <strong>shared with AV vendors</strong> (paid API access).<br>- Avoid submitting sensitive files.</p>                                                              |
| [**Hybrid Analysis**](https://www.hybrid-analysis.com/) | <p>- <strong>Free sandbox</strong> (Windows 10/11 VMs).<br>- Records API calls, network traffic, and file changes.<br>- Option to <strong>keep samples private</strong> (non-public).</p> | <p>- Free tier has limited submissions.<br>- Commercial version for on-prem use (<a href="https://www.crowdstrike.com/products/threat-intelligence/falcon-sandbox/">Falcon Sandbox</a>).</p> |
| [**Any.Run**](https://any.run/)                         | <p>- <strong>Interactive sandbox</strong> (control VM in real-time).<br>- Great for analyzing ransomware or C2 traffic.</p>                                                               | - Free tier limited; paid plans for full features.                                                                                                                                           |
| [**Joe Sandbox**](https://www.joesandbox.com/)          | <p>- Detailed <strong>PDF reports</strong> with IOCs.<br>- Supports Windows/Linux/Android analysis.</p>                                                                                   | - Free version has minimal features.                                                                                                                                                         |

***

**3. When to Use Which Tool**

* **Quick AV Check**: VirusTotal (e.g., "Is this file already flagged by AV?").
* **Deep Behavioral Analysis**: Hybrid Analysis/Any.Run (e.g., "What does this malware do when executed?").
* **Enterprise Needs**: Commercial sandboxes (e.g., Falcon Sandbox for internal use).

***

**4. Limitations & Risks**

* **Evasion Tactics**: Malware may detect sandboxes and remain dormant (e.g., checking for VM artifacts).
* **Privacy Issues**: Assume anything uploaded to VirusTotal becomes public to AV vendors.
* **False Negatives**: Clean results don’t guarantee safety—malware might be too new or obfuscated.

***

**5. Pro Tips**

1. **Hash Check First**:

   ```bash
   sha256sum suspicious_file.exe  # Compare with VirusTotal before uploading.  
   ```
2. **Use Private Mode**: On Hybrid Analysis, toggle "**Do not share my sample**" for sensitive files.
3. **Correlate IOCs**: Extract IPs, domains, and hashes to block in firewalls/SIEMs.

***

**Example Workflow**:

1. Find `invoice.exe` on a compromised system.
2. Upload to **VirusTotal**: 5/70 AVs flag it as `Emotet`.
3. Submit to **Hybrid Analysis**: Sandbox shows it drops a DLL and connects to `185.63.90.1`.
4. **Action**: Block the IP, hunt for other infections using the DLL’s hash.

### <mark style="color:blue;">**Monitoring Malware Behavior – Using VM**</mark>&#x20;

**1. Prepare the Environment**

* **Isolated Lab**: Use a **VM** (VirtualBox, VMware) or dedicated physical machine.
* **Disable Networking**: Prevent accidental infections (use host-only mode if internet access is needed).
* **Baseline Snapshot**: Take a **clean VM snapshot** before execution for easy reset.

**2. Enable Monitoring Tools**

| **Tool**            | **Purpose**                                     |
| ------------------- | ----------------------------------------------- |
| **Process Monitor** | Logs file/registry/process activity.            |
| **Wireshark**       | Captures network traffic.                       |
| **ProcExplorer**    | Monitors process tree and DLLs.                 |
| **Process Hacker**  | Tracks memory/CPU usage and handles.            |
| **API Monitor**     | Records Windows API calls (e.g., `CreateFile`). |

**3. Execute the Malware**

* **Run the sample**: Double-click or use CLI (e.g., `cmd.exe /c malware.exe`).
* **Optional Interaction**: Mimic user actions (e.g., clicking buttons in a fake installer).

**4. Terminate & Analyze**

* **Kill the Process**: Use **Task Manager** or:

  ```bash
  taskkill /IM malware.exe /F  # Windows  
  killall malware.exe          # Linux  
  ```
* **Pause Logging**: Stop all monitoring tools to preserve logs.

**5. Review Artifacts**

Look for:

* **Persistence Mechanisms**:
  * New registry keys (`Run`, `Services`).
  * Scheduled tasks (`schtasks /query`).
* **Network Activity**:
  * Suspicious IPs/domains (e.g., `185.63.90.1`).
  * Unusual ports (e.g., beaconing to `:443`).
* **File Changes**:
  * Files dropped in `%AppData%`, `%Temp%`.
  * DLL sideloading in `C:\Windows\System32\`.

**6. Reset & Repeat**

* **Revert to Snapshot**: Ensure a clean slate for the next test.

***

#### **Example Workflow**

1. **Setup**:
   * Start a Windows 10 VM (snapshot: `Clean_Baseline`).
   * Open **Process Monitor** (filter: `malware.exe`).
2. **Run**: Execute `invoice.exe`.
3. **Findings**:
   * Creates `C:\Users\Public\payload.dll`.
   * Connects to `91.205.77.123:8443`.
   * Adds `HKCU\Software\Microsoft\Windows\CurrentVersion\Run\UpdateHelper`.
4. **Action**:
   * Block IP in firewall.
   * Hunt for `payload.dll` hashes enterprise-wide.

***

#### **Key Considerations**

* **Evasion Tactics**: Some malware detects VMs/sandboxes (check for VM artifacts like `vmware.sys`).
* **Safety**: Never run malware on a production or networked machine.
* **Automation**: Use **Cuckoo Sandbox** for hands-off analysis.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://muhammed-hatem.gitbook.io/muhammed-hatem/summaries/sec-504-notes/sec504.1.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
