The defender's perspective: how every attack from Phases 2โ5 gets detected, investigated, and stopped.
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.
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.
When a security breach occurs, the Incident Response (IR) process is the structured approach to handling it. The NIST framework defines six phases:
# 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)
# 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?
# 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!)
# 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
# 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
# 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
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.
# 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 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 |
|---|---|---|---|
| 4624 | Security | Successful logon | Track who logged in, when, and from where (Logon Type matters!) |
| 4625 | Security | Failed logon | Brute force detection โ many 4625s followed by a 4624 = compromised |
| 4688 | Security | New process created | Track process execution โ see cmd.exe, powershell.exe, whoami.exe |
| 4720 | Security | User account created | Attacker creating persistence accounts |
| 4732 | Security | User added to group | Privilege escalation โ user added to Administrators group |
| 7045 | System | New service installed | Malware persistence โ services run at boot with SYSTEM privileges |
| 4648 | Security | Logon with explicit credentials | Lateral movement โ runas, PsExec, credential pass-through |
| 4672 | Security | Special privileges assigned | Admin/SYSTEM logon โ high-privilege activity starting |
| 1102 | Security | Audit log cleared | Log tampering โ attacker covering tracks (HUGE red flag) |
| 4104 | PowerShell | Script block logging | Records 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.
# 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 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.
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;)
Signature-based detection catches known attacks. Behavioral/anomaly detection catches the unknown by flagging deviations from normal:
# 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
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.
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 |
|---|---|---|
| Reconnaissance | Active Scanning (T1595), Gather Victim Info (T1589) | Phase 2: Nmap, OSINT |
| Initial Access | Exploit Public-Facing App (T1190), Phishing (T1566) | Phase 3: SQLi, File Upload |
| Execution | Command and Scripting (T1059), Exploitation for Execution (T1203) | Phase 3: Command Injection, SSTI |
| Persistence | Create Account (T1136), Scheduled Task (T1053), Server Software Component (T1505) | Phase 4: Web shells, cron jobs |
| Privilege Escalation | Exploitation (T1068), Sudo Abuse (T1548), Token Manipulation (T1134) | Phase 4: Linux/Windows PrivEsc |
| Defense Evasion | Indicator Removal (T1070), Obfuscation (T1027) | Phase 6: Log clearing (Event 1102) |
| Credential Access | OS Credential Dumping (T1003), Brute Force (T1110), Kerberoasting (T1558.003) | Phase 4: John/Hashcat, Phase 5: AD |
| Lateral Movement | Pass the Hash (T1550.002), Remote Services (T1021) | Phase 5: Pivoting, AD |
| Exfiltration | Exfiltration Over C2 (T1041), DNS Exfiltration (T1048.003) | Phase 6: Network monitoring |
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.
# 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)
# 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.
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).
# 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.
# 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 is the process of understanding what a malicious program does, how it works, and what indicators it leaves behind. There are two main approaches:
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
}
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.
Can you explain these without looking them up?
C:\Windows\System32\.alert http any any -> $HOME_NET any (msg:"SQLi attempt"; http_uri; sid:1000010; rev:1;)
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./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.