kavklaw@llm ~ /learn/phase-6
โ† Back to Learning Path

Phase 6: Blue Team & Defensive Security

The defender's perspective: how every attack from Phases 2โ€“5 gets detected, investigated, and stopped.

06

Phase 6: Blue Team & Defensive Security

Incident response, SIEM (Security Information and Event Management), log analysis, IDS/IPS (Intrusion Detection/Prevention Systems), malware analysis, and MITRE ATT&CK. The defender's side of every attack you've learned.

๐Ÿ”ต Why You Need This

Every technique from Phases 2โ€“5 leaves traces โ€” logs, network signatures, file artifacts, registry changes. Knowing what defenders see makes you stealthier on red team ops, helps you write reports that explain detection gaps, and opens doors to SOC (Security Operations Center โ€” the team that monitors and responds to threats 24/7), IR (Incident Response), and threat hunting roles.

๐Ÿšจ Incident Response โ€” The IR Process

When a security breach occurs, the Incident Response (IR) process is the structured approach to handling it. The NIST framework defines six phases:

The Six Phases of Incident Response

  1. Preparation โ€” Before incidents happen: establish IR plans, assemble the team, deploy monitoring tools, create runbooks, conduct tabletop exercises. This is 90% of IR.
    # Preparation checklist:
    - IR plan document with roles and escalation paths
    - Contact lists (legal, management, PR, law enforcement)
    - Forensic workstation ready (SIFT โ€” a Linux distro pre-loaded with forensics tools, REMnux โ€” a distro built for malware analysis)
    - Jump bags with USB drives, write blockers, forensic tools
    - Pre-authorized access to critical systems
    - Backup verification and restore testing
    - Regular tabletop exercises (simulate ransomware, data breach, insider threat)
  2. Identification โ€” Detect that an incident is occurring: analyze alerts, triage severity, determine scope. Ask: What happened? When? What systems are affected? Is it ongoing?
    # Identification signals:
    - SIEM alerts (failed logins, unusual processes, lateral movement)
    - IDS/IPS alerts (network signatures matching known attacks)
    - User reports ("my files are encrypted", "strange email from IT")
    - Anomaly detection (unusual outbound traffic at 3 AM)
    - Threat intel feeds matching your IOCs
    
    # Triage questions:
    # 1. Is this a true positive or false positive?
    # 2. What is the blast radius? (one user? one server? entire domain?)
    # 3. Is the attack still in progress?
    # 4. What data/systems are at risk?
  3. Containment โ€” Stop the bleeding. Two phases: short-term (isolate affected systems NOW) and long-term (patch the entry point while maintaining evidence).
    # Short-term containment (IMMEDIATE):
    # Isolate the host from the network
    netsh advfirewall set allprofiles firewallpolicy blockinbound,blockoutbound  # Windows
    iptables -P INPUT DROP; iptables -P OUTPUT DROP  # Linux
    
    # Disable compromised accounts
    net user compromised_user /active:no  # Windows
    passwd -l compromised_user            # Linux
    
    # Block attacker IPs at the firewall
    # Block C2 (Command & Control โ€” the attacker's server that controls the malware) domains in DNS
    
    # Long-term containment:
    # Apply patches to the exploited vulnerability
    # Rotate all credentials that may have been exposed
    # Set up enhanced monitoring on affected systems
    # Create forensic images BEFORE cleaning (evidence!)
  4. Eradication โ€” Remove the threat completely: delete malware, close backdoors, patch vulnerabilities, reset compromised credentials.
    # Eradication steps:
    # 1. Remove malware and backdoors from ALL affected systems
    # 2. Patch the vulnerability that was exploited
    # 3. Reset ALL passwords (not just the ones you know are compromised)
    # 4. Revoke and reissue certificates if needed
    # 5. Check for persistence mechanisms:
    #    - Scheduled tasks / cron jobs
    #    - Registry run keys (Windows)
    #    - Startup folders
    #    - WMI event subscriptions
    #    - SSH authorized_keys
    #    - Web shells in document roots
    # 6. Re-image compromised systems if unsure of full compromise scope
  5. Recovery โ€” Bring systems back online carefully: restore from clean backups, monitor closely, validate security controls.
    # Recovery process:
    # 1. Restore systems from verified clean backups
    # 2. Apply all security patches before going live
    # 3. Implement additional monitoring for 30-90 days
    # 4. Gradually restore network connectivity
    # 5. Verify business functionality
    # 6. Watch for re-infection indicators
    
    # Enhanced monitoring during recovery:
    # - Full packet capture on critical segments
    # - Increased logging verbosity
    # - File integrity monitoring (AIDE, OSSEC, Tripwire)
    # - Honey tokens and canary files
  6. Lessons Learned โ€” Within 2 weeks: document what happened, what worked, what failed, and update procedures. This is where organizations actually improve.
    # Post-incident review document:
    ## Timeline of events (UTC timestamps)
    ## Root cause analysis
    ## What detection worked / failed
    ## Response effectiveness
    ## Gaps in tooling or process
    ## Recommended improvements
    ## Updated runbooks and playbooks
๐Ÿง  Knowledge Check โ€” Incident Response
A user reports that their files have been encrypted and a ransom note is displayed. You're the IR lead. What is your FIRST action?
Containment first! Isolating the machine prevents the ransomware from spreading to other systems via network shares or lateral movement. You must also preserve evidence โ€” don't format or wipe anything yet. A forensic image of the encrypted machine may help identify the ransomware variant, find decryption keys, or support law enforcement. Paying ransom is discouraged (no guarantee of recovery, funds criminal operations).
Put the NIST Incident Response phases in the correct order:
Containment
Eradication
Identification
Lessons Learned
Preparation
Recovery
The correct NIST IR order: Preparation โ†’ Identification โ†’ Containment โ†’ Eradication โ†’ Recovery โ†’ Lessons Learned. Preparation happens before any incident. Identification detects and confirms the incident. Containment stops the spread. Eradication removes the threat. Recovery restores operations. Lessons Learned improves future response.

๐Ÿ“‹ Log Analysis โ€” Reading the Story of an Attack

Logs are the black box recorder of a security incident. Every attack leaves traces in logs โ€” if you know where to look and what to look for.

Linux Log Analysis

# Key Linux log files:
/var/log/auth.log          # Authentication events (SSH, sudo, su)
/var/log/syslog            # General system events
/var/log/kern.log          # Kernel messages (driver issues, module loads)
/var/log/apache2/access.log # Web server access (GET/POST requests)
/var/log/apache2/error.log  # Web server errors
/var/log/cron.log          # Cron job execution
/var/log/fail2ban.log      # Brute force detection/blocking
~/.bash_history            # User command history

# Hunting for SSH brute force:
grep "Failed password" /var/log/auth.log | awk '{print $11}' | sort | uniq -c | sort -rn | head
# Shows: top attacking IPs by number of failed SSH attempts

# Hunting for successful logins after brute force:
grep "Accepted password" /var/log/auth.log | grep -f <(grep "Failed password" /var/log/auth.log | awk '{print $11}' | sort -u)
# Cross-references: IPs that had both failed AND successful logins

# Suspicious sudo activity:
grep "sudo:" /var/log/auth.log | grep -v "pam_unix"
# Look for: unusual users running sudo, commands accessing /etc/shadow, etc.

# Web shell detection in access logs:
grep -E "cmd=|exec=|system=|passthru=|shell_exec=" /var/log/apache2/access.log
# Pattern: repeated requests to a single file with command parameters

# Finding new user creation:
grep "new user" /var/log/auth.log
# Attacker persistence: creating a new user account

Windows Event Log Analysis

Windows Event Logs are the primary source of forensic evidence on Windows systems. These are the critical Event IDs you must know:

Event ID Log Meaning Why It Matters
4624SecuritySuccessful logonTrack who logged in, when, and from where (Logon Type matters!)
4625SecurityFailed logonBrute force detection โ€” many 4625s followed by a 4624 = compromised
4688SecurityNew process createdTrack process execution โ€” see cmd.exe, powershell.exe, whoami.exe
4720SecurityUser account createdAttacker creating persistence accounts
4732SecurityUser added to groupPrivilege escalation โ€” user added to Administrators group
7045SystemNew service installedMalware persistence โ€” services run at boot with SYSTEM privileges
4648SecurityLogon with explicit credentialsLateral movement โ€” runas, PsExec, credential pass-through
4672SecuritySpecial privileges assignedAdmin/SYSTEM logon โ€” high-privilege activity starting
1102SecurityAudit log clearedLog tampering โ€” attacker covering tracks (HUGE red flag)
4104PowerShellScript block loggingRecords full PowerShell scripts โ€” reveals attack commands
# Windows Event Log analysis with PowerShell:

# Find failed logon attempts (brute force detection)
Get-WinEvent -FilterHashtable @{LogName='Security'; Id=4625} |
  Select-Object TimeCreated, @{N='IP';E={$_.Properties[19].Value}},
  @{N='User';E={$_.Properties[5].Value}} | Sort-Object TimeCreated

# Find successful logons (check Logon Type!)
Get-WinEvent -FilterHashtable @{LogName='Security'; Id=4624} |
  Where-Object {$_.Properties[8].Value -in @(3,10)} |
  Select-Object TimeCreated, @{N='User';E={$_.Properties[5].Value}},
  @{N='LogonType';E={$_.Properties[8].Value}},
  @{N='SourceIP';E={$_.Properties[18].Value}}
# Logon Type 3 = Network (SMB, WinRM)
# Logon Type 10 = Remote Desktop (RDP)

# Find new services installed (persistence)
Get-WinEvent -FilterHashtable @{LogName='System'; Id=7045} |
  Select-Object TimeCreated, @{N='ServiceName';E={$_.Properties[0].Value}},
  @{N='ImagePath';E={$_.Properties[1].Value}}

# Find new user accounts created
Get-WinEvent -FilterHashtable @{LogName='Security'; Id=4720} |
  Select-Object TimeCreated, @{N='NewUser';E={$_.Properties[0].Value}},
  @{N='Creator';E={$_.Properties[4].Value}}

# Detect log clearing (anti-forensics)
Get-WinEvent -FilterHashtable @{LogName='Security'; Id=1102}
# If you see this: someone cleared the security log. Major red flag.

# PowerShell script block logging (see what attackers ran)
Get-WinEvent -FilterHashtable @{LogName='Microsoft-Windows-PowerShell/Operational'; Id=4104} |
  Where-Object {$_.Message -match 'Invoke-Mimikatz|Invoke-Empire|base64|IEX|WebClient'}
๐Ÿ’ก Real-world tip: When doing IR, always check timestamps across all logs together. An attacker's footprint looks like: 4625s (brute force) โ†’ 4624 Type 3 (successful login) โ†’ 4688 (process creation โ€” whoami, net user) โ†’ 4732 (added to admin group) โ†’ 7045 (installed persistent service). This timeline tells the full story.

Practical Exercise: Analyze a Simulated Breach

# Exercise: Given these log entries, reconstruct the attack timeline:
#
# 2026-02-01 02:15:03 - Event 4625 (Failed logon) User: administrator, Source: 192.168.1.105 (x247 times)
# 2026-02-01 02:31:17 - Event 4624 (Successful logon) User: administrator, Type 3, Source: 192.168.1.105
# 2026-02-01 02:31:45 - Event 4688 (Process created) Process: whoami.exe, Parent: cmd.exe
# 2026-02-01 02:32:01 - Event 4688 (Process created) Process: net.exe, CmdLine: "net user backdoor P@ss123 /add"
# 2026-02-01 02:32:05 - Event 4720 (Account created) New user: backdoor, Created by: administrator
# 2026-02-01 02:32:15 - Event 4688 (Process created) Process: net.exe, CmdLine: "net localgroup administrators backdoor /add"
# 2026-02-01 02:32:18 - Event 4732 (User added to group) User: backdoor, Group: Administrators
# 2026-02-01 02:35:00 - Event 7045 (Service installed) Name: WindowsUpdateSvc, Path: C:\temp\beacon.exe
#
# Questions:
# 1. What was the initial attack vector? (brute force โ†’ password spray)
# 2. What was the attacker's first post-exploitation action? (whoami โ†’ situational awareness)
# 3. How did the attacker establish persistence? (new user + new service)
# 4. What IOCs can you extract? (IP: 192.168.1.105, File: C:\temp\beacon.exe, User: backdoor)

๐ŸŒ Network Monitoring โ€” IDS/IPS and Traffic Analysis

Network monitoring tools watch traffic patterns and compare them against known attack signatures and behavioral baselines. Understanding these systems helps you (a) detect attacks and (b) evade detection during red team operations.

IDS vs IPS โ€” Detection vs Prevention

  • IDS (Intrusion Detection System) โ€” Monitors and alerts. Sits passively on a network tap or SPAN port (a switch feature that mirrors traffic to a monitoring port). Sees everything, blocks nothing. Examples: Snort (detection mode), Suricata, Zeek (Bro).
  • IPS (Intrusion Prevention System) โ€” Monitors and blocks. Sits inline (traffic passes through it). Can drop malicious packets in real-time. Examples: Snort (inline mode), Suricata (IPS mode), Palo Alto.
  • NIDS (Network-based) โ€” Monitors network traffic at strategic chokepoints.
  • HIDS (Host-based) โ€” Monitors activity on individual hosts (file changes, process execution). Examples: OSSEC, Wazuh, Sysmon (a free Microsoft tool that adds detailed process, network, and file-change logging to Windows).

Snort/Suricata Rules โ€” Reading and Writing Detection Signatures

Snort and Suricata are open-source IDS/IPS engines. They inspect network traffic and match it against rules you write. Each rule describes a suspicious pattern โ€” if the traffic matches, the engine fires an alert (or blocks it, in IPS mode).

# Snort/Suricata rule structure:
# action protocol src_ip src_port -> dest_ip dest_port (options)

# Example: Detect Nmap SYN scan
alert tcp any any -> $HOME_NET any (msg:"Possible Nmap SYN scan"; \
  flags:S; threshold:type both, track by_src, count 100, seconds 10; \
  classtype:attempted-recon; sid:1000001; rev:1;)

# Example: Detect reverse shell (bash -i over TCP)
alert tcp $HOME_NET any -> $EXTERNAL_NET any (msg:"Reverse shell detected - bash interactive"; \
  content:"/bin/bash"; content:"-i"; within:20; \
  flow:established,to_server; classtype:trojan-activity; sid:1000002; rev:1;)

# Example: Detect SQL injection in HTTP traffic
alert http any any -> $HOME_NET any (msg:"SQL Injection attempt - UNION SELECT"; \
  content:"UNION"; nocase; content:"SELECT"; nocase; distance:0; within:20; \
  http_uri; classtype:web-application-attack; sid:1000003; rev:1;)

# Example: Detect Mimikatz usage (common in AD attacks)
alert tcp any any -> any any (msg:"Possible Mimikatz - sekurlsa"; \
  content:"sekurlsa"; nocase; content:"logonpasswords"; nocase; \
  classtype:trojan-activity; sid:1000004; rev:1;)

# Example: Detect data exfiltration via DNS (large TXT queries)
alert dns any any -> any any (msg:"Suspicious DNS TXT query - possible exfiltration"; \
  dns_query; content:"."; pcre:"/^[a-zA-Z0-9]{30,}\./"; \
  classtype:policy-violation; sid:1000005; rev:1;)

Network Baselines and Anomaly Detection

Signature-based detection catches known attacks. Behavioral/anomaly detection catches the unknown by flagging deviations from normal:

  • Traffic volume baselines: If a workstation typically sends 50MB/day but suddenly pushes 5GB outbound at 2 AM โ€” that's exfiltration.
  • Connection patterns: An internal server connecting to a Tor exit node or a known C2 IP? Unusual.
  • Protocol anomalies: DNS queries with 200+ character subdomain labels? Probably DNS tunneling. HTTP POSTs to random IPs on port 443? Possible C2.
  • Beaconing detection: C2 frameworks communicate at regular intervals (every 60 seconds, every 5 minutes). Frequency analysis of connections to external IPs can reveal this.
# Using Wireshark for network forensics:

# Capture traffic on an interface
sudo wireshark -i eth0 &

# Useful Wireshark display filters for SOC analysts:
http.request.method == "POST"               # All POST requests
dns.qry.name contains "suspicious"          # DNS queries for suspicious domains
tcp.flags.syn == 1 && tcp.flags.ack == 0    # SYN packets only (scanning)
ip.src == 10.10.10.50 && tcp.dstport == 4444  # Traffic from compromised host to C2
frame.len > 1000 && dns                     # Suspiciously large DNS packets
tcp.stream eq 5                             # Follow a specific TCP stream

# Using tshark (command-line Wireshark) for automated analysis:
tshark -r capture.pcap -Y "http.request" -T fields -e ip.src -e http.host -e http.request.uri
tshark -r capture.pcap -Y "dns.qry.type == 1" -T fields -e dns.qry.name | sort | uniq -c | sort -rn | head

๐ŸŽฎ Practice Network Monitoring

  • TryHackMe โ€” Snort room: Learn to write and tune Snort rules
  • TryHackMe โ€” Wireshark 101: Guided packet analysis exercises
  • TryHackMe โ€” NetworkMiner room: Network forensics tool practice
  • Malware Traffic Analysis (.net): Free PCAPs from real malware infections to analyze
  • Our Wireshark Guide โ€” Deep dive into traffic capture and analysis

๐ŸŽฏ Threat Detection โ€” MITRE ATT&CK Framework

The MITRE ATT&CK framework is the gold standard knowledge base of adversary tactics, techniques, and procedures (TTPs). It organizes everything an attacker does into a matrix that defenders use to build detection strategies.

Understanding the ATT&CK Matrix

ATT&CK organizes attacks into 14 tactics (the "why" โ€” the attacker's goal) and hundreds of techniques (the "how" โ€” specific methods). Every attack technique from Phases 2โ€“5 maps to ATT&CK:

ATT&CK Tactic Example Techniques Our Learning Path Reference
ReconnaissanceActive Scanning (T1595), Gather Victim Info (T1589)Phase 2: Nmap, OSINT
Initial AccessExploit Public-Facing App (T1190), Phishing (T1566)Phase 3: SQLi, File Upload
ExecutionCommand and Scripting (T1059), Exploitation for Execution (T1203)Phase 3: Command Injection, SSTI
PersistenceCreate Account (T1136), Scheduled Task (T1053), Server Software Component (T1505)Phase 4: Web shells, cron jobs
Privilege EscalationExploitation (T1068), Sudo Abuse (T1548), Token Manipulation (T1134)Phase 4: Linux/Windows PrivEsc
Defense EvasionIndicator Removal (T1070), Obfuscation (T1027)Phase 6: Log clearing (Event 1102)
Credential AccessOS Credential Dumping (T1003), Brute Force (T1110), Kerberoasting (T1558.003)Phase 4: John/Hashcat, Phase 5: AD
Lateral MovementPass the Hash (T1550.002), Remote Services (T1021)Phase 5: Pivoting, AD
ExfiltrationExfiltration Over C2 (T1041), DNS Exfiltration (T1048.003)Phase 6: Network monitoring

Indicators of Compromise (IOCs) vs Indicators of Attack (IOAs)

These are two different ways defenders look for threats. Think of IOCs as clues left behind after a crime, and IOAs as suspicious behavior that suggests a crime is happening right now.

  • IOCs (Indicators of Compromise) โ€” Static forensic artifacts that indicate a system has been compromised: file hashes, known malicious IP addresses, C2 domain names, registry keys, mutex names, email addresses. IOCs are reactive โ€” they identify known threats after the fact.
    # IOC examples:
    # File hash: e99a18c428cb38d5f260853678922e03 (known malware)
    # IP address: 185.220.101.34 (known C2 server)
    # Domain: evil-update.com (phishing domain)
    # File path: C:\Windows\Temp\beacon.exe
    # Registry key: HKLM\Software\Microsoft\Windows\CurrentVersion\Run\UpdateSvc
    # Email: [email protected] (phishing sender)
  • IOAs (Indicators of Attack) โ€” Behavioral patterns that indicate an attack is in progress, regardless of the specific malware. More durable than IOCs because they focus on attacker behavior, not specific tools:
    # IOA examples:
    # Behavior: Process injection (any process injecting code into another)
    # Behavior: Credential dumping (any tool accessing LSASS memory)
    # Behavior: Lateral movement pattern (authenticate โ†’ whoami โ†’ net user โ†’ net group)
    # Behavior: DNS beaconing (regular interval DNS queries to unusual domains)
    # Behavior: Scheduled task creating outbound connections
    # Behavior: PowerShell downloading and executing in memory (fileless)
๐Ÿ’ก Key insight: IOCs are like wanted posters โ€” they work until the attacker changes their face. IOAs are like suspicious behavior patterns โ€” an attacker can change tools but the behavior pattern remains. The best detection strategies combine both.

๐Ÿ“Š SIEM Basics โ€” Centralized Security Monitoring

A SIEM (Security Information and Event Management) system collects logs from every source in your environment, normalizes them, correlates events, and generates alerts. It's the nerve center of a SOC (Security Operations Center).

How a SIEM Works

  1. Collection: Ingest logs from firewalls, servers, endpoints, applications, cloud services, network devices
  2. Normalization: Convert all log formats into a common schema (different sources log the same events differently)
  3. Correlation: Connect related events across sources โ€” e.g., firewall allows connection + web server logs SQLi + endpoint creates new process = attack chain
  4. Detection: Rules and machine learning identify known attack patterns and anomalies
  5. Alerting: Notify analysts with context, severity, and recommended actions
  6. Investigation: Analysts drill into alerts, pivot across data sources, determine if it's a true/false positive

Popular SIEM Platforms

  • Splunk: The industry leader. Powerful SPL (Search Processing Language). Expensive but incredibly capable. Free trial and Splunk Enterprise Security for learning.
  • Elastic SIEM (ELK Stack): Open-source: Elasticsearch + Logstash + Kibana. Free, flexible, widely used. Great for home labs.
  • Microsoft Sentinel: Cloud-native SIEM built on Azure. KQL (Kusto Query Language). Growing rapidly in enterprise.
  • Wazuh: Open-source SIEM + XDR (Extended Detection and Response โ€” combines endpoint, network, and cloud monitoring in one platform). Excellent for learning โ€” full-featured and free.

Writing Detection Rules

# Splunk SPL โ€” Detect brute force (10+ failed logins from same IP in 5 min)
index=windows EventCode=4625
| stats count by src_ip, Account_Name
| where count > 10
| sort -count

# Splunk SPL โ€” Detect lateral movement (Pass the Hash)
index=windows EventCode=4624 Logon_Type=3
| where Account_Name!="ANONYMOUS LOGON" AND Account_Name!="*$"
| stats dc(dest) as unique_hosts by src_ip, Account_Name
| where unique_hosts > 5
| sort -unique_hosts

# ELK/KQL โ€” Detect new service installation (persistence)
event.code: "7045" AND NOT winlog.event_data.ImagePath: ("C:\\Windows\\System32\\*")

# ELK/KQL โ€” Detect PowerShell download cradle
event.code: "4104" AND winlog.event_data.ScriptBlockText: (*DownloadString* OR *WebClient* OR *IEX* OR *Invoke-Expression*)

# Sigma rule โ€” a universal detection rule format that works across SIEMs.
# Write once, convert to Splunk SPL, ELK KQL, Microsoft Sentinel, etc.:
title: Suspicious Process Creation - Recon Commands
status: experimental
description: Detects common reconnaissance commands used after initial compromise
logsource:
  category: process_creation
  product: windows
detection:
  selection:
    CommandLine|contains:
      - 'whoami'
      - 'net user'
      - 'net group "domain admins"'
      - 'ipconfig /all'
      - 'systeminfo'
      - 'nltest /dclist'
  condition: selection
  timeframe: 5m
  | count() by Computer > 3
level: medium
tags:
  - attack.discovery
  - attack.t1033
  - attack.t1069
๐Ÿ’ก Sigma rules are a universal detection rule format that can be converted to Splunk SPL, ELK KQL, Microsoft Sentinel, QRadar, and more. Writing Sigma rules means you write once, deploy anywhere. The SigmaHQ repository has thousands of community-contributed rules.

๐Ÿงช Practice: Set Up a Home SIEM Lab

# Quick ELK Stack setup with Docker (for learning):
git clone https://github.com/deviantony/docker-elk.git
cd docker-elk
docker compose up -d

# Access Kibana at http://localhost:5601
# Default creds: elastic / changeme

# Ingest sample data:
# 1. Download Windows event log samples from EVTX-ATTACK-SAMPLES on GitHub
# 2. Use Winlogbeat or manually import into Elasticsearch
# 3. Create detection rules in Kibana โ†’ Security โ†’ Rules

# Alternative: TryHackMe SIEM rooms:
# - "Splunk 101" โ€” Learn SPL basics
# - "Splunk: Exploring SPL" โ€” Advanced queries
# - "Investigating with ELK 101" โ€” KQL and Kibana
# - "Wazuh" โ€” Open-source SIEM/XDR setup and usage

๐Ÿ”ฌ Malware Analysis โ€” Introduction

Malware analysis is the process of understanding what a malicious program does, how it works, and what indicators it leaves behind. There are two main approaches:

Static Analysis โ€” Examining Without Executing

Analyze the malware without running it. Safe but limited โ€” you see the code, not necessarily the behavior.

# Step 1: Get basic file info
file suspicious.exe                    # File type
md5sum suspicious.exe                  # Hash for VirusTotal lookup
sha256sum suspicious.exe
strings suspicious.exe | less          # Readable strings (URLs, IPs, commands)
strings suspicious.exe | grep -i "http\|ftp\|cmd\|powershell\|reg\|192\.\|10\."

# Step 2: PE (Portable Executable) analysis โ€” PE is the file format for Windows
# .exe and .dll files. Use PE-bear, pestudio, or CFF Explorer to inspect them.
# Check: imports (what APIs does it call?), sections, resources, timestamps
# Suspicious imports: VirtualAlloc, WriteProcessMemory, CreateRemoteThread
#   โ†’ Process injection capability
# Suspicious imports: InternetOpen, URLDownloadToFile, HttpSendRequest
#   โ†’ Network communication / download capability
# Suspicious imports: RegSetValueEx, CreateService
#   โ†’ Persistence mechanisms

# Step 3: Disassembly / Decompilation
# Ghidra (free, by the NSA) or IDA Pro (paid, industry standard) โ€” these tools
# convert compiled programs back into readable assembly/pseudo-code
# Look for: C2 communication logic, encryption routines, persistence mechanisms

# Step 4: YARA rules โ€” pattern matching for malware
# YARA is like "grep for malware" โ€” you write rules that describe patterns
# (strings, byte sequences, file properties) and YARA scans files to find matches.
# Security teams use YARA rules to detect and classify malware across their systems.
rule SuspiciousStrings {
    meta:
        description = "Detect common malicious strings"
    strings:
        $s1 = "cmd.exe /c" nocase
        $s2 = "powershell -enc" nocase
        $s3 = "FromBase64String" nocase
        $s4 = "HKLM\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run"
        $url = /https?:\/\/[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}/
    condition:
        uint16(0) == 0x5A4D and 3 of them  // MZ header (PE file) + 3 matching strings
}

Dynamic Analysis โ€” Observing Behavior in a Sandbox

Run the malware in an isolated environment and watch what it does. Reveals actual behavior including network connections, file changes, and registry modifications.

# Sandboxing tools:
# - ANY.RUN (online, interactive sandbox โ€” watch malware execute in browser)
# - Cuckoo Sandbox (self-hosted, automated analysis)
# - Joe Sandbox (online, detailed reports)
# - Windows Sandbox (built into Win 10/11 Pro โ€” quick disposable environment)
# - REMnux (Linux VM pre-loaded with malware analysis tools โ€” strings, disassemblers, network tools)
# - FlareVM (Windows VM with analysis tools โ€” from Mandiant, the incident response company)

# What to monitor during dynamic analysis:
# Process activity: What processes does it create? Does it inject into others?
# File system: What files does it create/modify/delete?
# Registry: What keys does it add? (persistence check!)
# Network: What IPs/domains does it contact? What data does it send?
# API calls: What system functions does it invoke?

# Tools for monitoring during execution:
# Process Monitor (ProcMon) โ€” file system + registry + process activity
# Process Explorer โ€” process tree, loaded DLLs, handles
# Wireshark/FakeDNS โ€” capture network traffic
# Regshot โ€” snapshot registry before/after execution
โš ๏ธ CRITICAL: Never run malware on your real machine or a connected network. Always use an isolated VM with no network access (or only monitored/faked network). Snapshot before execution, revert after. Treat every sample as if it's the most dangerous malware you've ever seen.

๐ŸŽฎ Practice Malware Analysis & Digital Forensics

  • TryHackMe โ€” MAL: Malware Introductory: Guided malware analysis exercises
  • TryHackMe โ€” DFIR: An Introduction: Digital forensics and incident response
  • ANY.RUN โ€” Upload samples and watch them execute in a sandbox (free tier available)
  • Malware Bazaar (bazaar.abuse.ch): Free malware sample repository for research
  • CyberDefenders.org: Free blue team CTF challenges (PCAP analysis, memory forensics, log analysis)
  • Our Forensics & Steganography Guide โ€” Evidence analysis techniques

๐Ÿ‹๏ธ Practical Exercises

  1. Log analysis: Download the EVTX-ATTACK-SAMPLES from GitHub. Analyze them and reconstruct the attack timeline using only Event IDs 4624, 4625, 4688, 4720, and 7045.
  2. Write Snort rules: Install Snort on your Kali VM. Write rules to detect (a) port scans, (b) SQL injection in HTTP traffic, (c) reverse shell connections on port 4444.
  3. SIEM lab: Set up ELK Stack with Docker. Ingest Windows event logs and create a dashboard showing failed logins, new process creation, and new service installations.
  4. MITRE ATT&CK mapping: Take the "Your First Box" walkthrough from this page and map every step to its ATT&CK technique ID. Create a navigator layer showing your coverage.
  5. Malware analysis: Download a sample from Malware Bazaar. Perform static analysis only: strings, PE headers, hash lookup on VirusTotal. Document your findings.
  6. Incident response tabletop: Write an IR scenario (ransomware hitting a small business) and walk through all 6 NIST phases. Document your decisions and actions.

โœ… Key Concepts Checklist

Can you explain these without looking them up?

  • Name the six phases of NIST incident response in order.
  • What Windows Event ID indicates a failed logon? A successful logon? A new service?
  • What's the difference between an IDS and an IPS?
  • Explain the difference between IOCs and IOAs with examples.
  • What does a SIEM do and why is log correlation important?
  • What is MITRE ATT&CK and how do defenders use it?
  • What's the difference between static and dynamic malware analysis?
  • Why should you never clear logs during an active investigation?

๐ŸŽค Common Interview Questions (SOC/IR Roles)

  • "Walk me through how you would respond to a ransomware incident."
  • "What Windows Event IDs would you look at to detect lateral movement?"
  • "How would you detect a Pass-the-Hash attack in your SIEM?"
  • "Explain the difference between a SIEM and an IDS."
  • "You see 5,000 failed login attempts from the same IP in 10 minutes. What do you do?"
  • "How would you detect data exfiltration over DNS?"
  • "What is the MITRE ATT&CK framework and how do you use it in your daily work?"

๐Ÿ“š Resources for This Phase

Our Guides
External Resources
  • MITRE ATT&CK โ€” The adversary tactics and techniques knowledge base
  • SigmaHQ โ€” Universal detection rule format and community rules
  • CyberDefenders.org โ€” Free blue team CTF challenges
  • LetsDefend.io โ€” SOC analyst training with simulated alerts
  • TryHackMe โ€” SOC Level 1 path โ€” Structured blue team training
๐Ÿ“

Phase 6 Checkpoint

0 / 8
Which Windows Event ID indicates that a new service has been installed on the system?
Event ID 7045 (System log) fires when a new service is installed. This is a critical persistence indicator โ€” attackers install malicious services to survive reboots and run with SYSTEM privileges. During IR, always check 7045 events for services with suspicious names or executable paths outside C:\Windows\System32\.
Scenario: You're reviewing SIEM alerts and notice 3,000 Event ID 4625 (failed logon) entries from IP 192.168.1.50 targeting the "administrator" account over 15 minutes, followed by a single Event ID 4624 (successful logon) from the same IP. What happened and what should you do?
This is a textbook brute force โ†’ compromise pattern. 3,000 failed attempts followed by a success means the password was cracked. Immediate actions: (1) Disable or isolate the compromised account, (2) Block the source IP, (3) Check for post-compromise activity (4688 process events, 4720 new accounts, 7045 new services), (4) Look for lateral movement to other systems, (5) Reset the admin password and investigate the source.
What is the key difference between an IDS and an IPS?
An IDS sits on a network tap/SPAN port passively โ€” it sees all traffic and generates alerts but cannot stop attacks. An IPS sits inline (traffic passes through it) and can actively drop or block malicious packets in real-time. The trade-off: IPS can prevent attacks but may cause disruptions from false positives blocking legitimate traffic.
Complete this Snort rule to detect HTTP traffic containing "UNION SELECT" (SQL injection):
Fill in the blank:
alert http any any -> $HOME_NET any (msg:"SQLi attempt";  http_uri; sid:1000010; rev:1;)
The content keyword matches byte patterns in the packet payload. Using nocase makes it case-insensitive (attackers often use mixed case like "uNiOn SeLeCt" to bypass naive detection). The http_uri keyword restricts the match to the HTTP URI only, reducing false positives from body content.
What is the purpose of the MITRE ATT&CK framework for defenders?
MITRE ATT&CK catalogs real-world adversary behavior into tactics (the "why") and techniques (the "how"). Defenders use it to: (1) Map their detection rules to specific techniques, (2) Identify gaps in detection coverage, (3) Prioritize which detections to build based on threat intelligence, (4) Communicate about threats using a common language. It's not a scanner or vulnerability list โ€” it's a behavioral knowledge base.
During malware analysis, what is the main advantage of dynamic analysis over static analysis?
Dynamic analysis shows what the malware actually does when it runs โ€” network callbacks to C2 servers, files it drops, registry keys it creates, processes it injects into. Static analysis shows what the code looks like, but heavily obfuscated or packed malware may hide its true behavior from static inspection. The downside: dynamic analysis requires running the malware in a safe sandbox, and some malware detects sandbox environments and changes its behavior.
Which log file on a Linux system would you check to investigate SSH brute force attempts?
/var/log/auth.log (Debian/Ubuntu) or /var/log/secure (RHEL/CentOS) records all authentication events including SSH login attempts, sudo usage, and su commands. To find brute force attacks, search for "Failed password" entries and group by source IP.
What Windows Event ID indicates that the security audit log was cleared (potential evidence tampering)?
Event ID 1102 fires when the Security event log is cleared. This is a major red flag during an investigation โ€” legitimate admins rarely clear security logs, and attackers do it to cover their tracks. If you see 1102, immediately check other log sources (Sysmon, PowerShell, network logs) for evidence the attacker tried to destroy.
โ† Red Team Capstone All Phases Phase 7: Career Paths โ†’