Chapter 4.4 - Hardening Playbooks, Compliance & Red/Blue Team Exercises
Module 4: Defense Engineering & Hardening Final Chapter - Course Capstone Prerequisites: All previous chapters. This chapter synthesizes offensive knowledge (Module 3) with defensive architecture (Module 4) into operational practice.
Table of Contents
- Hardening Philosophy - CIS Benchmarks & Defense-in-Depth
- Windows Hardening Playbook
- Linux Hardening Playbook
- Network Device & Infrastructure Hardening
- Compliance Frameworks - NIST, CIS, SOC 2 & PCI-DSS
- Vulnerability Management - Scanning, Prioritization & Remediation
- Red Team Operations - Planning, Rules of Engagement & Reporting
- Blue Team Detection Validation & Purple Team Exercises
- Security Metrics & Continuous Improvement
- MITRE ATT&CK Mapping & Course Summary
1. Hardening Philosophy - CIS Benchmarks & Defense-in-Depth
Why Hardening Fails in Practice
Most organizations apply hardening controls inconsistently - they harden new systems at build time but drift occurs over months as patches are missed, exceptions are granted, and configurations are changed for convenience. The result is a heterogeneous environment where hardening is the exception rather than the rule.
The three failure modes:
| Failure Mode | Root Cause | Consequence |
|---|---|---|
| Configuration drift | No continuous compliance monitoring | Hardened at build; vulnerable 6 months later |
| Exception sprawl | No exception review process | Every "temporary" exception becomes permanent |
| Coverage gaps | Hardening applied to servers but not workstations | Attackers pivot through ungoverned endpoints |
CIS Benchmark Levels
The Center for Internet Security (CIS) publishes benchmarks for every major OS, cloud platform, and application. Each benchmark has two implementation levels:
- Level 1: Minimum baseline - essential controls with low operational impact. Every organization should meet L1 on all systems.
- Level 2: Strict hardening - additional controls that may impact functionality. Appropriate for high-security environments (DMZ, servers handling PII/PHI).
# CIS-CAT Lite -- free benchmark assessment tool
# Download from: https://www.cisecurity.org/cis-cat-lite
# Run assessment against local system (Linux)
./CIS-CAT.sh \
-b benchmarks/CIS_Ubuntu_Linux_22.04_LTS_Benchmark_v1.0.0-xccdf.xml \
-p xccdf_org.cisecurity.benchmarks_profile_Level_1_-_Server \
-r /tmp/cis_assessment \
-html # HTML report output
# OpenSCAP -- open-source compliance scanner (Linux)
apt install openscap-scanner scap-security-guide
# Assess against CIS profile
oscap xccdf eval \
--profile xccdf_org.ssgproject.content_profile_cis_server_l1 \
--results /tmp/scan_results.xml \
--report /tmp/scan_report.html \
/usr/share/xml/scap/ssg/content/ssg-ubuntu2204-ds.xml
# Parse results: pass/fail counts
oscap xccdf generate report /tmp/scan_results.xml | \
grep -E "pass|fail" | sort | uniq -c
Defense-in-Depth Model
No single control stops all attacks. Defense-in-depth layers controls such that bypassing one layer still requires defeating multiple others:
Layer 1: Perimeter -> Firewall, IPS, WAF, email gateway
Layer 2: Network -> Segmentation, micro-seg, NAC, encrypted transport
Layer 3: Endpoint -> EDR, AV, host firewall, application allowlisting
Layer 4: Identity -> MFA, PAM, least-privilege, privileged access workstations
Layer 5: Data -> Encryption at rest, DLP, rights management
Layer 6: Detection -> SIEM, SOAR, threat hunting, behavioral analytics
Layer 7: Response -> IR plan, playbooks, backups, disaster recovery
The offensive chapters (Module 3) demonstrated that every individual layer can be bypassed. The power of defense-in-depth is that bypassing all layers simultaneously is exponentially harder.
2. Windows Hardening Playbook
Core Windows Hardening - PowerShell
# ==================================================
# WINDOWS HARDENING PLAYBOOK
# Based on CIS Windows 10/11 Benchmark Level 1
# Run as Administrator
# ==================================================
# -------------------------------------------------
# 1. ACCOUNT POLICY
# -------------------------------------------------
# Password policy
net accounts /minpwlen:14 # Minimum 14-character passwords
net accounts /maxpwage:90 # 90-day maximum password age
net accounts /minpwage:1 # 1-day minimum (prevents immediate re-use)
net accounts /uniquepw:24 # Remember 24 passwords
# Lockout policy
net accounts /lockoutthreshold:5 # Lock after 5 failed attempts
net accounts /lockoutduration:15 # Lock for 15 minutes
net accounts /lockoutwindow:15 # Reset counter after 15 minutes
# Disable built-in Administrator and Guest accounts
Disable-LocalUser -Name "Administrator"
Disable-LocalUser -Name "Guest"
# Rename built-in Administrator (obfuscation layer)
Rename-LocalUser -Name "Administrator" -NewName "LocalAdmin_Disabled"
# -------------------------------------------------
# 2. AUDIT POLICY -- ENABLE CRITICAL LOGGING
# -------------------------------------------------
# Process creation with command line (feeds SIEM detections)
auditpol /set /subcategory:"Process Creation" /success:enable /failure:enable
reg add "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System\Audit" `
/v ProcessCreationIncludeCmdLine_Enabled /t REG_DWORD /d 1 /f
# Logon/Logoff events
auditpol /set /subcategory:"Logon" /success:enable /failure:enable
auditpol /set /subcategory:"Logoff" /success:enable
auditpol /set /subcategory:"Account Lockout" /success:enable /failure:enable
# Privilege use
auditpol /set /subcategory:"Sensitive Privilege Use" /success:enable /failure:enable
# Object access (file/registry)
auditpol /set /subcategory:"File System" /success:enable /failure:enable
auditpol /set /subcategory:"Registry" /success:enable /failure:enable
# Account management
auditpol /set /subcategory:"User Account Management" /success:enable /failure:enable
auditpol /set /subcategory:"Security Group Management" /success:enable /failure:enable
# PowerShell logging
reg add "HKLM\SOFTWARE\Policies\Microsoft\Windows\PowerShell\ScriptBlockLogging" `
/v EnableScriptBlockLogging /t REG_DWORD /d 1 /f
reg add "HKLM\SOFTWARE\Policies\Microsoft\Windows\PowerShell\Transcription" `
/v EnableTranscripting /t REG_DWORD /d 1 /f
reg add "HKLM\SOFTWARE\Policies\Microsoft\Windows\PowerShell\Transcription" `
/v OutputDirectory /t REG_SZ /d "\\LOGSERVER\PSTranscripts$" /f
# Increase Security event log size (default 20MB is insufficient)
wevtutil sl Security /ms:1073741824 # 1 GB
wevtutil sl System /ms:524288000 # 500 MB
# -------------------------------------------------
# 3. NETWORK HARDENING
# -------------------------------------------------
# Disable SMBv1 (EternalBlue)
Set-SmbServerConfiguration -EnableSMB1Protocol $false -Force
Disable-WindowsOptionalFeature -Online -FeatureName SMB1Protocol -NoRestart
# Require SMB signing (prevents NTLM relay)
Set-SmbServerConfiguration -RequireSecuritySignature $true -Force
Set-SmbClientConfiguration -RequireSecuritySignature $true -Force
# Disable LLMNR (prevents Responder attacks)
reg add "HKLM\SOFTWARE\Policies\Microsoft\Windows NT\DNSClient" `
/v EnableMulticast /t REG_DWORD /d 0 /f
# Disable NBT-NS (prevents Responder attacks)
$adapters = Get-WmiObject Win32_NetworkAdapterConfiguration | Where-Object {$_.IPEnabled}
foreach ($adapter in $adapters) { $adapter.SetTcpipNetbios(2) }
# Disable WDigest (prevents cleartext password storage in LSASS)
reg add "HKLM\SYSTEM\CurrentControlSet\Control\SecurityProviders\WDigest" `
/v UseLogonCredential /t REG_DWORD /d 0 /f
# Enable Credential Guard (protects LSASS with virtualization)
# Requires: UEFI Secure Boot + Virtualization Based Security capable hardware
reg add "HKLM\SYSTEM\CurrentControlSet\Control\DeviceGuard" `
/v EnableVirtualizationBasedSecurity /t REG_DWORD /d 1 /f
reg add "HKLM\SYSTEM\CurrentControlSet\Control\DeviceGuard" `
/v RequirePlatformSecurityFeatures /t REG_DWORD /d 1 /f
reg add "HKLM\SYSTEM\CurrentControlSet\Control\Lsa" `
/v LsaCfgFlags /t REG_DWORD /d 1 /f
# Disable NTLMv1 (force NTLMv2 minimum)
reg add "HKLM\SYSTEM\CurrentControlSet\Control\Lsa" `
/v LmCompatibilityLevel /t REG_DWORD /d 5 /f
# 5 = send NTLMv2 only, refuse LM and NTLMv1
# -------------------------------------------------
# 4. ATTACK SURFACE REDUCTION (ASR)
# -------------------------------------------------
# Enable Windows Defender ASR rules
# Block Office apps from spawning child processes
Add-MpPreference -AttackSurfaceReductionRules_Ids `
"d4f940ab-401b-4efc-aadc-ad5f3c50688a" `
-AttackSurfaceReductionRules_Actions Enabled
# Block credential stealing from LSASS
Add-MpPreference -AttackSurfaceReductionRules_Ids `
"9e6c4e1f-7d60-472f-ba1a-a39ef669e4b3" `
-AttackSurfaceReductionRules_Actions Enabled
# Block process creation from PSExec and WMI commands
Add-MpPreference -AttackSurfaceReductionRules_Ids `
"d1e49aac-8f56-4280-b9ba-993a6d77406c" `
-AttackSurfaceReductionRules_Actions Enabled
# Block Office from injecting code into other processes
Add-MpPreference -AttackSurfaceReductionRules_Ids `
"75668c1f-73b5-4cf0-bb93-3ecf5cb7cc84" `
-AttackSurfaceReductionRules_Actions Enabled
# -------------------------------------------------
# 5. LSASS PROTECTION
# -------------------------------------------------
# Enable LSA Protection (RunAsPPL) -- prevents Mimikatz from reading LSASS
reg add "HKLM\SYSTEM\CurrentControlSet\Control\Lsa" `
/v RunAsPPL /t REG_DWORD /d 1 /f
# Requires reboot; after reboot, Mimikatz requires kernel-level access
# -------------------------------------------------
# 6. APPLOCKER / APPLICATION CONTROL
# -------------------------------------------------
# Create AppLocker policy -- whitelist approach
# Allow only signed executables from Program Files
$policy = @"
<AppLockerPolicy Version="1">
<RuleCollection Type="Exe" EnforcementMode="Enabled">
<FilePublisherRule Id="1" Name="Signed by Microsoft" Action="Allow"
UserOrGroupSid="S-1-1-0">
<Conditions><FilePublisherCondition PublisherName="O=MICROSOFT CORPORATION"
ProductName="*" BinaryName="*" VersionRange="*"/></Conditions>
</FilePublisherRule>
<FilePathRule Id="2" Name="Program Files" Action="Allow"
UserOrGroupSid="S-1-1-0">
<Conditions><FilePathCondition Path="%PROGRAMFILES%\*"/></Conditions>
</FilePathRule>
<FilePathRule Id="3" Name="Windows" Action="Allow"
UserOrGroupSid="S-1-1-0">
<Conditions><FilePathCondition Path="%WINDIR%\*"/></Conditions>
</FilePathRule>
<!-- DENY: execution from user-writable locations -->
<FilePathRule Id="4" Name="Block Temp" Action="Deny"
UserOrGroupSid="S-1-1-0">
<Conditions><FilePathCondition Path="%TEMP%\*"/></Conditions>
</FilePathRule>
<FilePathRule Id="5" Name="Block AppData" Action="Deny"
UserOrGroupSid="S-1-1-0">
<Conditions><FilePathCondition Path="%LOCALAPPDATA%\*"/></Conditions>
</FilePathRule>
</RuleCollection>
</AppLockerPolicy>
"@
Set-AppLockerPolicy -XMLPolicy $policy
Validate Windows Hardening
# Verify critical settings are applied
function Test-Hardening {
$results = @()
# SMBv1 disabled?
$smb1 = (Get-SmbServerConfiguration).EnableSMB1Protocol
$results += [PSCustomObject]@{
Check="SMBv1 Disabled"; Pass=(-not $smb1); Value=$smb1}
# WDigest disabled?
$wdigest = (Get-ItemProperty "HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\WDigest" `
-Name UseLogonCredential -EA SilentlyContinue).UseLogonCredential
$results += [PSCustomObject]@{
Check="WDigest Disabled"; Pass=($wdigest -eq 0); Value=$wdigest}
# LLMNR disabled?
$llmnr = (Get-ItemProperty "HKLM:\SOFTWARE\Policies\Microsoft\Windows NT\DNSClient" `
-Name EnableMulticast -EA SilentlyContinue).EnableMulticast
$results += [PSCustomObject]@{
Check="LLMNR Disabled"; Pass=($llmnr -eq 0); Value=$llmnr}
# SMB signing required?
$signing = (Get-SmbServerConfiguration).RequireSecuritySignature
$results += [PSCustomObject]@{
Check="SMB Signing Required"; Pass=$signing; Value=$signing}
# PowerShell ScriptBlock logging?
$pslog = (Get-ItemProperty `
"HKLM:\SOFTWARE\Policies\Microsoft\Windows\PowerShell\ScriptBlockLogging" `
-Name EnableScriptBlockLogging -EA SilentlyContinue).EnableScriptBlockLogging
$results += [PSCustomObject]@{
Check="PS ScriptBlock Logging"; Pass=($pslog -eq 1); Value=$pslog}
$results | Format-Table -AutoSize
$pass = ($results | Where-Object {$_.Pass}).Count
Write-Host "$pass / $($results.Count) checks passed" -ForegroundColor $(
if ($pass -eq $results.Count) {'Green'} else {'Red'})
}
Test-Hardening
3. Linux Hardening Playbook
# ==================================================
# LINUX HARDENING PLAYBOOK
# Based on CIS Ubuntu 22.04 LTS Benchmark Level 1
# ==================================================
# -------------------------------------------------
# 1. KERNEL PARAMETERS
# -------------------------------------------------
cat >> /etc/sysctl.d/99-hardening.conf << 'EOF'
# Network hardening
net.ipv4.ip_forward = 0 # Disable IP forwarding (non-router)
net.ipv4.conf.all.send_redirects = 0 # Don't send ICMP redirects
net.ipv4.conf.all.accept_redirects = 0 # Don't accept ICMP redirects
net.ipv4.conf.all.accept_source_route = 0 # Disable source routing
net.ipv4.conf.all.log_martians = 1 # Log packets with impossible addresses
net.ipv4.conf.all.rp_filter = 1 # Enable reverse path filtering
net.ipv4.tcp_syncookies = 1 # SYN flood protection
net.ipv6.conf.all.disable_ipv6 = 1 # Disable IPv6 if not needed
# Memory protection
kernel.randomize_va_space = 2 # Full ASLR
kernel.exec-shield = 1 # NX bit enforcement
kernel.dmesg_restrict = 1 # Restrict dmesg (prevents info leak)
kernel.kptr_restrict = 2 # Hide kernel pointers
kernel.perf_event_paranoid = 3 # Restrict perf events
kernel.yama.ptrace_scope = 1 # Restrict ptrace (blocks some injection)
# Filesystem
fs.suid_dumpable = 0 # Disable SUID core dumps
fs.protected_hardlinks = 1 # Prevent hardlink attacks
fs.protected_symlinks = 1 # Prevent symlink attacks
EOF
sysctl -p /etc/sysctl.d/99-hardening.conf
# -------------------------------------------------
# 2. FILESYSTEM HARDENING
# -------------------------------------------------
# Mount options -- restrict execution in writable locations
cat >> /etc/fstab << 'EOF'
# Harden temporary filesystems
tmpfs /tmp tmpfs defaults,nodev,nosuid,noexec 0 0
tmpfs /var/tmp tmpfs defaults,nodev,nosuid,noexec 0 0
tmpfs /dev/shm tmpfs defaults,nodev,nosuid,noexec 0 0
EOF
mount -o remount /tmp
mount -o remount /var/tmp
mount -o remount /dev/shm
# Find and fix world-writable files and directories
find / -not \( -path /proc -prune \) -not \( -path /sys -prune \) \
-perm -o+w -type f 2>/dev/null | \
while read file; do
chmod o-w "$file"
echo "Fixed: $file"
done
# -------------------------------------------------
# 3. USER & ACCOUNT HARDENING
# -------------------------------------------------
# Password policy (PAM)
cat > /etc/security/pwquality.conf << 'EOF'
minlen = 14 # Minimum 14 characters
minclass = 4 # All four character classes required
maxrepeat = 2 # Max 2 consecutive identical chars
maxclassrepeat = 4 # Max 4 consecutive same-class chars
lcredit = -1 # Require at least 1 lowercase
ucredit = -1 # Require at least 1 uppercase
dcredit = -1 # Require at least 1 digit
ocredit = -1 # Require at least 1 special char
EOF
# Password aging
sed -i 's/^PASS_MAX_DAYS.*/PASS_MAX_DAYS 90/' /etc/login.defs
sed -i 's/^PASS_MIN_DAYS.*/PASS_MIN_DAYS 1/' /etc/login.defs
sed -i 's/^PASS_WARN_AGE.*/PASS_WARN_AGE 14/' /etc/login.defs
# Restrict su to wheel group
echo "auth required pam_wheel.so use_uid" >> /etc/pam.d/su
# Lock inactive accounts
useradd -D -f 30 # Lock accounts after 30 days of inactivity
# Remove users with empty passwords
awk -F: '($2 == "" ) { print $1 }' /etc/shadow | \
while read user; do
echo "Locking empty-password account: $user"
passwd -l "$user"
done
# -------------------------------------------------
# 4. SSH HARDENING
# -------------------------------------------------
cat > /etc/ssh/sshd_config.d/hardening.conf << 'EOF'
# Protocol & Ciphers
Protocol 2
Ciphers chacha20-poly1305@openssh.com,aes256-gcm@openssh.com,aes128-gcm@openssh.com
MACs hmac-sha2-512-etm@openssh.com,hmac-sha2-256-etm@openssh.com
KexAlgorithms curve25519-sha256,curve25519-sha256@libssh.org,diffie-hellman-group16-sha512
# Authentication
PermitRootLogin no # No direct root SSH
PasswordAuthentication no # Key-based only
PermitEmptyPasswords no
PubkeyAuthentication yes
AuthorizedKeysFile .ssh/authorized_keys
MaxAuthTries 3 # Max 3 auth attempts per connection
LoginGraceTime 30 # 30s to authenticate
MaxSessions 4 # Max 4 sessions per connection
# Session
ClientAliveInterval 300 # 5-minute keepalive
ClientAliveCountMax 2 # Disconnect after 2 missed keepalives
TCPKeepAlive no # Use SSH-level keepalive instead
Compression no # Disable compression (past CRIME-like issues)
# Access control
AllowGroups ssh-users # Only users in ssh-users group can SSH
DenyUsers root administrator
# Disable dangerous features
X11Forwarding no
AllowAgentForwarding no
AllowTcpForwarding no # No SSH tunneling (unless needed)
GatewayPorts no
PermitUserEnvironment no
# Logging
LogLevel VERBOSE # Log fingerprint of keys used
SyslogFacility AUTH
EOF
# Regenerate host keys (remove weak DSA/ECDSA, keep only Ed25519 and RSA-4096)
rm /etc/ssh/ssh_host_*
ssh-keygen -t ed25519 -f /etc/ssh/ssh_host_ed25519_key -N ""
ssh-keygen -t rsa -b 4096 -f /etc/ssh/ssh_host_rsa_key -N ""
systemctl restart sshd
# -------------------------------------------------
# 5. AUDITD -- COMPREHENSIVE LOGGING
# -------------------------------------------------
cat > /etc/audit/rules.d/99-hardening.rules << 'EOF'
# Delete existing rules and set defaults
-D
-b 8192 # Buffer size
--backlog_wait_time 60000
# Immutable (lock rules -- requires reboot to change)
# Enable last, after all rules are set:
# -e 2
# Identity changes
-w /etc/passwd -p wa -k identity
-w /etc/group -p wa -k identity
-w /etc/shadow -p wa -k identity
-w /etc/sudoers -p wa -k sudoers
-w /etc/sudoers.d/ -p wa -k sudoers
# Privilege escalation
-a always,exit -F arch=b64 -S setuid -S setgid -F a0=0 -k privilege_esc
-a always,exit -F arch=b64 -S setresuid -S setresgid -k privilege_esc
# Root command execution
-a always,exit -F arch=b64 -S execve -F euid=0 -F auid!=0 -k root_cmd
-a always,exit -F arch=b32 -S execve -F euid=0 -F auid!=0 -k root_cmd
# Module loading (rootkit detection)
-w /sbin/insmod -p x -k module_load
-w /sbin/rmmod -p x -k module_load
-w /sbin/modprobe -p x -k module_load
-a always,exit -F arch=b64 -S init_module -S delete_module -k module_load
# Network configuration changes
-a always,exit -F arch=b64 -S sethostname -S setdomainname -k network_change
-w /etc/hosts -p wa -k network_change
-w /etc/network/ -p wa -k network_change
# Cron modifications (persistence)
-w /etc/cron.allow -p wa -k cron
-w /etc/cron.deny -p wa -k cron
-w /etc/cron.d/ -p wa -k cron
-w /etc/cron.daily/ -p wa -k cron
-w /etc/cron.hourly/ -p wa -k cron
-w /etc/crontab -p wa -k cron
-w /var/spool/cron/ -p wa -k cron
# SSH key modifications (persistence)
-w /root/.ssh -p wa -k ssh_keys
-a always,exit -F dir=/home -F name=.ssh -p wa -k ssh_keys
# Outbound connections (detect C2)
-a always,exit -F arch=b64 -S connect -k outbound_conn
# Make rules immutable (enable after all rules loaded)
-e 2
EOF
service auditd restart
auditctl -l | wc -l # Verify rules loaded
4. Network Device & Infrastructure Hardening
# -------------------------------------------------
# CISCO IOS HARDENING (reference -- not executable bash)
# -------------------------------------------------
# Service hardening -- disable unused services
# no service finger
# no service tcp-small-servers
# no service udp-small-servers
# no ip http server ! Disable HTTP management
# no ip http secure-server ! Use HTTPS only if needed
# no cdp run ! Disable CDP (info disclosure)
# no ip source-route
# AAA -- centralized authentication
# aaa new-model
# aaa authentication login default group tacacs+ local
# aaa authorization exec default group tacacs+ local
# aaa accounting exec default start-stop group tacacs+
# Console and VTY line hardening
# line console 0
# exec-timeout 5 0 ! 5-minute idle timeout
# logging synchronous
# line vty 0 4
# transport input ssh ! SSH only, no Telnet
# exec-timeout 10 0
# access-class 10 in ! Restrict by ACL 10
# SSH version 2 only
# ip ssh version 2
# ip ssh time-out 30
# ip ssh authentication-retries 3
# -------------------------------------------------
# NETWORK HARDENING VALIDATION
# -------------------------------------------------
# Test from external -- verify exposed services
nmap -sV -p- --open YOUR_PERIMETER_IP \
--script=banner \
-oG /tmp/perimeter_scan.txt
# Check for default credentials on discovered services
nmap -sV YOUR_PERIMETER_IP \
--script default,auth \
-p 22,23,80,443,161,8080,8443
# Test SNMP community strings
onesixtyone -c /usr/share/doc/onesixtyone/dict.txt \
YOUR_NETWORK_RANGE # Brute-force SNMP communities
# Verify TLS configuration of all HTTPS endpoints
testssl.sh --severity HIGH \
--parallel \
--csv /tmp/tls_results.csv \
https://YOUR_WEB_SERVER
# Checks: protocol versions, cipher suites, certificate validity,
# HSTS, HPKP, forward secrecy
5. Compliance Frameworks - NIST, CIS, SOC 2 & PCI-DSS
Framework Comparison
| Framework | Scope | Mandatory? | Key Focus | Assessment |
|---|---|---|---|---|
| NIST CSF | Any organization | No (voluntary) | Risk management lifecycle | Self-assessment |
| NIST SP 800-53 | US Federal agencies | Yes (FedRAMP) | 20 control families, 1000+ controls | Third-party assessment |
| CIS Controls v8 | Any organization | No | 18 prioritized control groups | Self/third-party |
| SOC 2 Type II | SaaS/cloud providers | No (customer-driven) | Trust Service Criteria (security, availability, confidentiality) | External auditor |
| PCI-DSS v4.0 | Cardholder data handlers | Yes (contractual) | 12 requirements for card data protection | QSA assessment |
| ISO 27001 | Any organization | No | ISMS (information security management system) | Certification body |
| HIPAA | US healthcare | Yes (law) | PHI protection | HHS/OCR investigation |
PCI-DSS - Technical Controls Mapping
PCI-DSS v4.0 has 12 requirements. The technical requirements map directly to controls covered in this course:
Req 1: Install and maintain network security controls
-> Chapter 4.1: Firewall architecture, segmentation, DMZ design
Req 2: Apply secure configurations
-> Chapter 4.4: CIS benchmarks, hardening playbooks
Req 3: Protect stored account data
-> Encryption at rest, key management, data masking
Req 4: Protect cardholder data in transit
-> Chapter 2.4: TLS inspection, cipher suite enforcement
Req 5: Protect against malicious software
-> EDR deployment, application allowlisting (this chapter)
Req 6: Develop and maintain secure systems
-> Vulnerability management (this chapter), SDLC security
Req 7: Restrict access by business need
-> Least privilege, PAM, Chapter 4.1 Zero Trust
Req 8: Identify users and authenticate access
-> MFA, Chapter 1.4 Authentication Protocols
Req 9: Restrict physical access
-> Physical security (out of scope for network course)
Req 10: Log and monitor all access
-> Chapter 4.2: SIEM, audit logging, log retention
Req 11: Test security regularly
-> Chapter 4.4: Penetration testing, vulnerability scanning
Req 12: Support information security with org policies
-> Policies, procedures, training
# PCI-DSS Req 11.3 -- Internal penetration test (required annually)
# Document the test scope, methodology, and findings
cat > /tmp/pentest_scope.txt << 'EOF'
PCI-DSS Penetration Test Scope
==============================
Scope: Cardholder Data Environment (CDE) and all systems
with connectivity to the CDE
In-Scope Systems:
- Payment processing servers: 10.50.1.0/24
- Database servers: 10.50.2.0/24
- Web application: https://payments.corp.com
- Network segmentation controls (firewall separating CDE from other networks)
Methodology: PTES (Penetration Testing Execution Standard)
+ OWASP Testing Guide for web applications
Required Tests:
- Network layer: port scanning, service enumeration, exploitation attempts
- Application layer: OWASP Top 10 assessment
- Segmentation test: verify CDE cannot be reached from out-of-scope networks
- Social engineering: phishing simulation targeting payment team
Frequency: Annually (minimum); after significant infrastructure changes
EOF
NIST CSF - Maturity Assessment
#!/usr/bin/env python3
# nist_csf_assessment.py -- evaluate maturity against NIST CSF 2.0 functions
csf_functions = {
"GOVERN": {
"description": "Organizational context, risk management strategy, policies",
"controls": [
("GV.OC-01", "Organizational mission understood and communicated", False),
("GV.RM-01", "Risk management policy exists and is approved", False),
("GV.PO-01", "Cybersecurity policy exists and is communicated", False),
]
},
"IDENTIFY": {
"description": "Asset management, risk assessment, improvement",
"controls": [
("ID.AM-01", "Hardware assets inventoried", False),
("ID.AM-02", "Software assets inventoried", False),
("ID.RA-01", "Vulnerabilities identified and documented", False),
("ID.RA-05", "Threats and vulnerabilities prioritized by risk", False),
]
},
"PROTECT": {
"description": "Identity management, access control, data security, hardening",
"controls": [
("PR.AA-01", "Identities managed for authorized users/services", False),
("PR.AA-05", "Access permissions enforced least-privilege", False),
("PR.DS-01", "Data at rest protected", False),
("PR.DS-02", "Data in transit protected", False),
("PR.IR-01", "Networks segmented", False),
]
},
"DETECT": {
"description": "Continuous monitoring, adverse event analysis",
"controls": [
("DE.CM-01", "Networks monitored for adverse events", False),
("DE.CM-03", "Personnel activity monitored for anomalies", False),
("DE.AE-02", "Potentially adverse events analyzed", False),
("DE.AE-06", "Information on adverse events provided to authorized staff", False),
]
},
"RESPOND": {
"description": "Incident management, analysis, mitigation, communication",
"controls": [
("RS.MA-01", "Incidents investigated per IR plan", False),
("RS.MA-02", "Incidents triaged and validated", False),
("RS.MI-01", "Incidents contained", False),
("RS.CO-02", "Incidents reported per legal/regulatory requirements", False),
]
},
"RECOVER": {
"description": "Incident recovery, communication, improvements",
"controls": [
("RC.RP-01", "Recovery plan executed during/after incidents", False),
("RC.CO-03", "Recovery activities communicated to stakeholders", False),
]
}
}
# Score your organization (set True for implemented controls)
# Example: set based on actual assessment
csf_functions["PROTECT"]["controls"][0] = ("PR.AA-01", "Identities managed", True)
csf_functions["DETECT"]["controls"][0] = ("DE.CM-01", "Networks monitored", True)
total = sum(len(v["controls"]) for v in csf_functions.values())
implemented = sum(
sum(1 for c in v["controls"] if c[2])
for v in csf_functions.values()
)
print(f"\nNIST CSF 2.0 Maturity Assessment")
print(f"{'='*50}")
for func, data in csf_functions.items():
func_total = len(data["controls"])
func_impl = sum(1 for c in data["controls"] if c[2])
pct = (func_impl/func_total)*100
bar = "#" * int(pct/10) + "." * (10-int(pct/10))
print(f"\n{func} -- {data['description']}")
print(f" [{bar}] {func_impl}/{func_total} ({pct:.0f}%)")
for ctrl_id, ctrl_name, impl in data["controls"]:
status = "[OK]" if impl else "[--]"
print(f" {status} {ctrl_id}: {ctrl_name}")
print(f"\n{'='*50}")
print(f"Overall: {implemented}/{total} ({implemented/total*100:.0f}%)")
6. Vulnerability Management - Scanning, Prioritization & Remediation
Vulnerability Scanning with OpenVAS/Nessus
# OpenVAS (open-source vulnerability scanner)
# Install via Greenbone Community Edition
apt install gvm
gvm-setup # Initial setup and feed download
# Start services
gvm-start
# Access web UI: https://localhost:9392
# CLI scanning
gvm-cli --gmp-username admin --gmp-password PASSWORD \
socket --xml \
"<create_target><name>Internal Scan</name><hosts>10.0.0.0/24</hosts></create_target>"
# Nessus CLI (commercial -- most widely used)
# /opt/nessus/sbin/nessuscli scan --policy "Basic Network Scan" \
# --targets "10.0.0.0/24" --output /tmp/scan_results.nessus
# Parse Nessus results for critical/high findings
python3 << 'EOF'
import xml.etree.ElementTree as ET
tree = ET.parse('/tmp/scan_results.nessus')
root = tree.getroot()
findings = []
for report_host in root.findall('.//ReportHost'):
hostname = report_host.get('name')
for item in report_host.findall('ReportItem'):
severity = int(item.get('severity', 0))
if severity >= 3: # Critical (4) or High (3)
findings.append({
'host': hostname,
'severity': ['Info','Low','Med','High','Critical'][severity],
'plugin': item.get('pluginName'),
'cve': item.findtext('cve', 'N/A'),
'cvss': item.findtext('cvss3_base_score', '0'),
'solution': item.findtext('solution', '')[:100],
})
findings.sort(key=lambda x: float(x['cvss'] or 0), reverse=True)
for f in findings[:20]:
print(f"[{f['severity']:8}] CVSS:{f['cvss']:4} | {f['host']:20} | "
f"{f['plugin'][:50]} | CVE: {f['cve']}")
EOF
CVSS-Based Prioritization with EPSS
Not all CVEs are equal. CVSS score alone is a poor prioritization signal - many critical-CVSS vulnerabilities are never exploited in the wild. EPSS (Exploit Prediction Scoring System) provides a probability of exploitation, dramatically improving prioritization:
#!/usr/bin/env python3
# vuln_prioritize.py -- prioritize vulnerabilities using CVSS + EPSS + context
import requests
import json
def get_epss_scores(cve_list):
"""Fetch EPSS scores from FIRST.org API"""
cves = ",".join(cve_list)
resp = requests.get(
f"https://api.first.org/data/1.0/epss?cve={cves}",
timeout=10
)
scores = {}
for item in resp.json().get('data', []):
scores[item['cve']] = {
'epss': float(item['epss']), # Probability of exploitation (0-1)
'percentile': float(item['percentile'])
}
return scores
def prioritize_vulns(vulnerabilities):
"""
Priority scoring:
CVSS Base Score (40%) + EPSS probability (40%) + Context multipliers (20%)
Context: internet-facing, privileged system, PII data
"""
cve_ids = [v['cve'] for v in vulnerabilities if v.get('cve')]
epss = get_epss_scores(cve_ids)
for vuln in vulnerabilities:
cve = vuln.get('cve', '')
cvss = float(vuln.get('cvss', 0))
epss_score = epss.get(cve, {}).get('epss', 0.0)
# Context multipliers
context_mult = 1.0
if vuln.get('internet_facing'): context_mult *= 1.5
if vuln.get('privileged_system'): context_mult *= 1.3
if vuln.get('pii_data'): context_mult *= 1.4
priority = ((cvss/10 * 0.4) + (epss_score * 0.4)) * context_mult * 100
vuln['priority_score'] = round(priority, 1)
vuln['epss'] = epss_score
return sorted(vulnerabilities, key=lambda x: x['priority_score'], reverse=True)
# Example usage
vulns = [
{'cve':'CVE-2021-44228', 'cvss': 10.0, 'host':'webserver01',
'internet_facing': True, 'pii_data': True, 'privileged_system': False},
{'cve':'CVE-2017-0144', 'cvss': 9.3, 'host':'fileserver02',
'internet_facing': False, 'pii_data': False, 'privileged_system': True},
{'cve':'CVE-2022-1292', 'cvss': 9.8, 'host':'vpn01',
'internet_facing': True, 'pii_data': False, 'privileged_system': False},
]
results = prioritize_vulns(vulns)
for v in results:
print(f"Priority: {v['priority_score']:5.1f} | EPSS: {v['epss']:.3f} | "
f"CVSS: {v['cvss']} | {v['cve']} on {v['host']}")
7. Red Team Operations - Planning, Rules of Engagement & Reporting
Red Team vs Penetration Test
| Dimension | Penetration Test | Red Team Operation |
|---|---|---|
| Objective | Find all vulnerabilities | Simulate specific adversary, test detection |
| Scope | Defined list of systems | Goal-based (e.g., "reach the domain controller") |
| Duration | Days to weeks | Weeks to months |
| Stealth | Not required | Explicit requirement |
| Notification | IT team notified | Blue team NOT notified (tests real detection) |
| Output | Vulnerability list + remediation | Attacker narrative, detection gaps, TTPs used |
| Cost | Lower | Higher |
Rules of Engagement Document
# RED TEAM ENGAGEMENT -- RULES OF ENGAGEMENT
## Engagement: Corp Red Team 2024-Q1
## Client: Target Corporation
## Dates: 2024-01-15 to 2024-02-15
### AUTHORIZATION
This document authorizes [Red Team Firm] to conduct adversary simulation
activities against [Target Corporation] infrastructure.
Authorized by: [CISO Name, Title, Signature]
Legal counsel reviewed: [Date]
### SCOPE
**In-Scope:**
- External IP ranges: [LIST]
- Internal network (post-initial access): 10.0.0.0/8
- Active Directory domain: corp.local
- Web applications: [LIST URLs]
**Explicitly Out-of-Scope (DO NOT TEST):**
- Production payment processing systems: 10.50.0.0/24
- Hospital/medical systems: 10.60.0.0/24
- Personal devices of employees
- Physical premises (no physical testing authorized)
- Denial of service attacks of any kind
### OBJECTIVES (RANKED)
1. Obtain Domain Admin credentials
2. Access financial reporting systems
3. Exfiltrate a sample document from the Finance share
4. Maintain persistence for 72 hours undetected
### CONSTRAINTS
- No destructive actions (no ransomware simulation, no data deletion)
- No social engineering of non-IT staff
- No exploitation of third-party systems (cloud providers, SaaS)
- All attacker infrastructure must be decommissioned within 48h of engagement end
### EMERGENCY CONTACT
If a genuinely critical vulnerability is found that poses immediate risk,
pause the engagement and notify:
- Primary: [CISO] [phone]
- Secondary: [IT Director] [phone]
- Deconfliction phrase: "DRAGONSFIRE"
### DATA HANDLING
All client data accessed during testing must be:
- Documented (filename, location, timestamp)
- Not exfiltrated to red team infrastructure
- Reported in findings with screenshot evidence only
Red Team Report Structure
# RED TEAM ASSESSMENT REPORT
## Executive Summary (1 page -- for C-suite)
- Engagement dates, scope summary
- Objectives achieved (e.g., "Domain Admin obtained in 8 hours")
- Critical risk rating with business impact
- Top 3 recommendations
## Attack Narrative (for IR/Security team)
### Initial Access
- Technique: Spearphishing (T1566.001)
- Target: helpdesk@corp.com
- Result: Meterpreter shell as helpdesk01\jsmith
- Time: Day 1, 14:32 EST
### Privilege Escalation
- Technique: Kerberoasting (T1558.003)
- Discovered SPN: MSSQLSvc/dbserver01:1433 (svc-mssql account)
- Cracked in: 4 hours (password: "Welcome1!")
- Pivoted to: DB server with svc-mssql credentials
[Continue for each phase...]
## Technical Findings (detailed)
### Finding 001: Spearphishing Leading to Code Execution
**Severity:** Critical
**MITRE ATT&CK:** T1566.001, T1059.001
**Evidence:** [screenshot]
**Reproduction Steps:** [detailed]
**Remediation:** Security awareness training + email gateway controls
## Detection Gaps
- Initial access: Not detected (phishing email bypassed gateway)
- Kerberoasting: Detected via Event 4769 but alert not actioned for 6 hours
- DCSync: Not detected (Event 4662 audit policy not configured on DC)
## Recommendations (prioritized by risk)
1. Enforce MFA on all remote access -- blocks initial access vector
2. Configure Event 4662 audit policy on DCs -- enables DCSync detection
3. Implement gMSA for svc-mssql -- defeats Kerberoasting
8. Blue Team Detection Validation & Purple Team Exercises
Purple Team Framework
Purple team exercises bridge the gap between red team findings and blue team detections - rather than a covert adversary simulation, both teams work together to validate and improve detections in real time.
# Purple team exercise workflow:
# 1. Red team announces: "I am going to execute technique T1003.001 (LSASS dumping)"
# 2. Blue team confirms: "We have a detection for this -- watching the SIEM"
# 3. Red team executes the technique
# 4. Both teams evaluate: did the detection fire? Was it accurate?
# 5. If detection missed: root cause analysis + rule improvement
# 6. If detection fired: validate accuracy, check for false positive potential
# Atomic Red Team -- granular TTP tests
# Install
Install-Module -Name invoke-atomicredteam -Scope CurrentUser -Force
Import-Module invoke-atomicredteam
# Run specific ATT&CK tests and validate detection
$tests = @(
@{Technique="T1003.001"; Name="LSASS Memory Dump"},
@{Technique="T1059.001"; Name="PowerShell Encoded Command"},
@{Technique="T1547.001"; Name="Registry Run Key Persistence"},
@{Technique="T1053.005"; Name="Scheduled Task Creation"},
@{Technique="T1558.003"; Name="Kerberoasting"}
)
foreach ($test in $tests) {
Write-Host "`n[*] Testing: $($test.Name) ($($test.Technique))"
Write-Host " Notify blue team: watching for $($test.Technique)"
Read-Host " Press Enter when blue team is ready"
# Execute test
Invoke-AtomicTest $test.Technique -TestNumbers 1 -Confirm:$false
Write-Host " Test executed at $(Get-Date -Format 'HH:mm:ss')"
$detected = Read-Host " Did alert fire in SIEM? (Y/N)"
if ($detected -eq "Y") {
Write-Host " [DETECTED]" -ForegroundColor Green
} else {
Write-Host " [MISSED] - investigation required" -ForegroundColor Red
}
# Cleanup
Invoke-AtomicTest $test.Technique -TestNumbers 1 -Cleanup -Confirm:$false
Start-Sleep 5
}
Detection Gap Analysis from Red Team Findings
#!/usr/bin/env python3
# gap_analysis.py -- map red team findings to detection coverage
red_team_findings = [
{"technique": "T1566.001", "name": "Spearphishing",
"detected": False, "detection_time_minutes": None},
{"technique": "T1059.001", "name": "PowerShell Cradle",
"detected": True, "detection_time_minutes": 180}, # 3 hours -- too slow
{"technique": "T1558.003", "name": "Kerberoasting",
"detected": True, "detection_time_minutes": 360}, # 6 hours -- unacceptable
{"technique": "T1003.006", "name": "DCSync",
"detected": False, "detection_time_minutes": None},
{"technique": "T1021.002", "name": "SMB Lateral Movement",
"detected": False, "detection_time_minutes": None},
{"technique": "T1547.001", "name": "Registry Persistence",
"detected": False, "detection_time_minutes": None},
]
print("RED TEAM FINDINGS -- DETECTION GAP ANALYSIS")
print("="*65)
detected = [f for f in red_team_findings if f["detected"]]
not_detected = [f for f in red_team_findings if not f["detected"]]
print(f"\n[DETECTED] ({len(detected)}/{len(red_team_findings)}):")
for f in detected:
t = f["detection_time_minutes"]
sla = "[OK] Within SLA" if t and t <= 60 else f"[WARN] {t}min (exceeds 60min SLA)"
print(f" {f['technique']} {f['name']:30} -> {sla}")
print(f"\n[MISSED] ({len(not_detected)}/{len(red_team_findings)}):")
for f in not_detected:
print(f" {f['technique']} {f['name']:30} -> COVERAGE GAP -- rule needed")
detection_rate = len(detected) / len(red_team_findings) * 100
print(f"\nDetection Rate: {detection_rate:.0f}%")
print(f"Mean Time to Detect (detected only): "
f"{sum(f['detection_time_minutes'] for f in detected if f['detection_time_minutes']) / max(len(detected),1):.0f} minutes")
9. Security Metrics & Continuous Improvement
Key Security Metrics
#!/usr/bin/env python3
# security_metrics.py -- calculate and track operational security KPIs
from datetime import datetime, timedelta
import statistics
# These would be pulled from SIEM/ticketing in production
sample_data = {
# Mean Time to Detect (MTTD) -- days from breach to detection
"mttd_days": [1, 3, 0.5, 7, 2, 1, 0.25, 4],
# Mean Time to Respond (MTTR) -- hours from detection to containment
"mttr_hours": [2, 8, 1, 24, 4, 2, 0.5, 12],
# Patch SLA compliance -- % of critical vulns patched within SLA (30 days)
"patch_sla": [True, True, False, True, True, False, True, True, True, True],
# Alert-to-actionable ratio -- % of alerts that become investigations
"alert_dispositions": ["TP","FP","FP","TP","FP","FP","FP","TP","FP","FP",
"TP","FP","TP","FP","FP","FP","FP","TP","FP","FP"],
# Phishing simulation click rate
"phishing_clicked": [True,False,False,True,False,False,False,True,False,False,
False,False,True,False,False,False,False,False,False,False],
}
print("SECURITY OPERATIONS METRICS DASHBOARD")
print("="*55)
mttd = sample_data["mttd_days"]
print(f"\nMean Time to Detect (MTTD)")
print(f" Mean: {statistics.mean(mttd):.1f} days")
print(f" Median: {statistics.median(mttd):.1f} days")
print(f" Target: < 1 day {'[OK]' if statistics.mean(mttd) < 1 else '[FAIL]'}")
mttr = sample_data["mttr_hours"]
print(f"\nMean Time to Respond (MTTR)")
print(f" Mean: {statistics.mean(mttr):.1f} hours")
print(f" Median: {statistics.median(mttr):.1f} hours")
print(f" Target: < 4 hours {'[OK]' if statistics.mean(mttr) < 4 else '[FAIL]'}")
patch = sample_data["patch_sla"]
patch_rate = sum(patch)/len(patch)*100
print(f"\nPatch SLA Compliance (Critical, 30-day)")
print(f" Rate: {patch_rate:.0f}%")
print(f" Target: > 95% {'[OK]' if patch_rate > 95 else '[FAIL]'}")
disp = sample_data["alert_dispositions"]
tp_rate = disp.count("TP")/len(disp)*100
print(f"\nAlert Fidelity (True Positive Rate)")
print(f" TP Rate: {tp_rate:.0f}%")
print(f" FP Rate: {100-tp_rate:.0f}%")
print(f" Target: > 20% TP {'[OK]' if tp_rate > 20 else '[FAIL]'}")
phish = sample_data["phishing_clicked"]
click_rate = sum(phish)/len(phish)*100
print(f"\nPhishing Simulation Click Rate")
print(f" Rate: {click_rate:.0f}%")
print(f" Target: < 5% {'[OK]' if click_rate < 5 else '[FAIL]'}")
10. MITRE ATT&CK Mapping & Course Summary
Complete Course ATT&CK Coverage
This course has covered detection and/or exploitation of the following ATT&CK techniques across all 16 chapters:
| Tactic | Key Techniques Covered | Primary Chapter |
|---|---|---|
| Reconnaissance | T1595, T1590, T1596, T1593 | 3.1 |
| Initial Access | T1190, T1566, T1078, T1465 | 3.2, 3.4 |
| Execution | T1059, T1047, T1053, T1204 | 3.2, 3.3 |
| Persistence | T1547, T1543, T1546, T1053 | 3.2, 3.3, 4.3 |
| Privilege Escalation | T1548, T1068, T1134 | 3.2, 3.3 |
| Defense Evasion | T1070, T1027, T1218, T1562 | 3.2, 4.3 |
| Credential Access | T1003, T1558, T1040, T1552 | 2.4, 3.3, 4.3 |
| Discovery | T1046, T1082, T1590 | 3.1 |
| Lateral Movement | T1021, T1550, T1557 | 3.3 |
| Collection | T1114, T1041, T1560 | 3.3, 4.3 |
| C2 | T1071, T1573, T1090, T1095 | 2.4, 3.2 |
| Exfiltration | T1041, T1048, T1052 | 2.4, 3.4 |
| Impact | T1485, T1486, T1489 | 4.3 (recovery) |
Course Completion - Key Takeaways
Every chapter in this course was written around a single unifying principle:
You cannot defend what you don't understand, and you cannot understand what you haven't seen from both sides.
The offensive chapters (Module 3) were not present to teach attacks - they were present to give defenders the mental model of an attacker. When you understand that Kerberoasting requires RC4-encrypted TGS requests, you know exactly what Event 4769 field to filter on. When you understand how LLMNR poisoning works, you know why disabling LLMNR is a first-day control rather than an advanced hardening measure.
The defensive chapters (Module 4) translate that understanding into durable controls: firewall architecture that structurally prevents lateral movement, detection rules that fire on attacker behavior rather than signatures, IR playbooks that sequence evidence collection correctly, and hardening baselines that remove the attack surface before it can be exploited.
Security is not a product - it is a continuous process of understanding the threat, reducing the attack surface, detecting what gets through, and improving after every test and every incident.
End of Chapter 4.4 - Hardening Playbooks, Compliance & Red/Blue Team Exercises
End of Module 4 - Defense Engineering & Hardening
Course Complete
Network Security - All 16 Chapters
Module 1: Foundations & Threat Landscape
- 1.1 Network Architecture & Attack Surfaces
- 1.2 Threat Intelligence & Attack Taxonomy
- 1.3 Cryptography in Network Security
- 1.4 Authentication Protocols & Identity Attacks
Module 2: Traffic Analysis & Intrusion Detection
- 2.1 Packet Analysis & Protocol Dissection
- 2.2 IDS/IPS - Signatures, Anomaly Detection & Evasion
- 2.3 Network Forensics & Log Analysis
- 2.4 Encrypted Traffic Analysis & TLS Inspection
Module 3: Offensive Security & Exploitation
- 3.1 Reconnaissance, Scanning & Enumeration
- 3.2 Exploitation Techniques - Network to Application Layer
- 3.3 Man-in-the-Middle, Spoofing & Lateral Movement
- 3.4 Wireless & VPN Attack Techniques
Module 4: Defense Engineering & Hardening
- 4.1 Firewall Architecture, Segmentation & Zero Trust
- 4.2 SIEM, SOAR & Detection Engineering
- 4.3 Incident Response & Digital Forensics
- 4.4 Hardening Playbooks, Compliance & Red/Blue Team Exercises