Using AI as your co-pilot to detect, contain, eradicate, and recover from security incidents faster and more effectively.
Respond to an active security incident — identify, contain, and eradicate the threat using AI-assisted IR techniques.
Incident response procedures are for authorized security operations and CTF competitions. In real incidents, follow your organization's established IR procedures and legal requirements.
Modern SOCs face alert volumes that overwhelm human analysts. AI transforms IR from a reactive scramble into a structured, accelerated workflow.
NIST Special Publication 800-61 Rev. 2 defines the standard incident response lifecycle used across government and industry.
| Phase | Purpose | AI Role |
|---|---|---|
| Preparation | Build IR capability before incidents occur | Generate playbooks, train scenarios |
| Detection & Analysis | Identify and validate incidents | Alert correlation, log analysis, severity scoring |
| Containment, Eradication & Recovery | Stop the threat, remove it, restore services | Recommend containment actions, verify eradication |
| Post-Incident Activity | Learn and improve | Root cause analysis, lessons-learned reports |
IR is a cycle, not a one-time event. Lessons from each incident feed back into preparation for the next.
The SANS Institute breaks IR into six discrete phases — more granular than NIST, making it ideal for operational playbooks.
NIST combines Containment, Eradication, and Recovery into one phase. SANS separates them for clearer operational focus.
AI can track which phase you are in and provide phase-specific recommendations, preventing analysts from jumping ahead.
Effective incident response starts long before the first alert fires. AI accelerates preparation by generating and maintaining IR documentation.
# AI-assisted playbook generation prompt
prompt = """Generate an IR playbook for ransomware incidents targeting
our environment:
- 200 Windows endpoints on 10.0.0.0/16
- Active Directory domain: corp.example.com
- Critical assets: SQL Server (10.0.5.10), File Server (10.0.5.20)
- Backup system: Veeam with air-gapped copies
Include: detection signatures, containment steps, eradication
checklist, recovery procedures, and communication templates."""
response = client.messages.create(
model="claude-sonnet-4-20250514",
max_tokens=4096,
messages=[{"role": "user", "content": prompt}]
)
The identification phase is where AI delivers the most immediate value: transforming a flood of alerts into actionable intelligence.
def ai_triage_alert(alert_data):
"""Use AI to classify and prioritize a security alert."""
prompt = f"""Analyze this security alert and provide:
1. Classification (True Positive / False Positive / Needs Investigation)
2. Severity (Critical / High / Medium / Low)
3. Attack category (MITRE ATT&CK technique if applicable)
4. Recommended immediate actions
5. Related IOCs to search for
Alert Data:
{json.dumps(alert_data, indent=2)}
Context: Enterprise network, 500 employees, Windows/Linux mixed env.
Normal business hours: 08:00-18:00 EST."""
response = client.messages.create(
model="claude-sonnet-4-20250514",
max_tokens=1024,
messages=[{"role": "user", "content": prompt}]
)
return parse_triage_response(response.content[0].text)
AI can apply a consistent severity assessment framework to every alert, reducing the variability between analyst shift handoffs.
| Factor | Critical | High | Medium | Low |
|---|---|---|---|---|
| Data at risk | PII / financial / classified | Internal sensitive | Internal general | Public data |
| Systems affected | Domain controller / auth | Production servers | Dev/staging | Individual workstation |
| Lateral movement | Confirmed spread | Indicators present | Possible | Isolated |
| Active exfiltration | Confirmed outbound | Suspicious DNS/HTTP | Anomalous traffic | None detected |
| Business impact | Revenue-generating down | Major function impaired | Minor disruption | No impact |
Feed the matrix to the AI as system context, then provide raw alert data. Ask the AI to score each factor and compute an overall severity with justification.
During an active incident, AI can continuously build and maintain a timeline from multiple log sources. Here is an example of an AI-generated incident timeline:
| Time (UTC) | Source | Event | Severity |
|---|---|---|---|
| 14:23:01 | EDR | Suspicious PowerShell execution on WS-042 | Medium |
| 14:23:18 | AD Logs | Service account svc_backup authenticates from WS-042 | High |
| 14:24:05 | Firewall | WS-042 connects to 185.220.101.x:443 (known C2) | Critical |
| 14:25:33 | EDR | Mimikatz signature detected in memory on WS-042 | Critical |
| 14:26:10 | AD Logs | svc_backup queries all domain admin group members | Critical |
| 14:28:44 | SIEM | Lateral movement: svc_backup authenticates to SRV-DB-01 | Critical |
| 14:30:02 | DLP | Large data transfer initiated from SRV-DB-01 to external IP | Critical |
Attack pattern identified: Initial access via compromised workstation → credential harvesting (Mimikatz) → privilege escalation (service account abuse) → lateral movement → data exfiltration. Matches MITRE ATT&CK chain: T1059.001 → T1003.001 → T1078.002 → T1021.002 → T1041.
During an active incident, feed real-time data to AI for continuous analysis and recommendations.
class IRCoPilot:
"""AI-driven incident response co-pilot."""
def __init__(self, client):
self.client = client
self.timeline = []
self.context = []
def analyze_event(self, event):
"""Analyze a new event in the context of the ongoing incident."""
self.timeline.append(event)
prompt = f"""You are an incident response co-pilot assisting a
SOC analyst during an active security incident.
INCIDENT TIMELINE SO FAR:
{json.dumps(self.timeline, indent=2)}
NEW EVENT:
{json.dumps(event, indent=2)}
Provide:
1. How this event relates to the existing incident timeline
2. Updated threat assessment (escalate/maintain/de-escalate)
3. Immediate recommended actions (be specific with commands)
4. What evidence to collect NOW before it is lost
5. Predicted next attacker actions based on the pattern"""
response = self.client.messages.create(
model="claude-sonnet-4-20250514",
max_tokens=2048,
messages=[{"role": "user", "content": prompt}]
)
return response.content[0].text
Containment is about stopping the bleeding. AI helps choose the right containment strategy based on the attack type, affected systems, and business impact.
AI can recommend containment actions, but a human must authorize execution. Isolating a production database server has business consequences that AI cannot fully evaluate.
AI generates specific, copy-paste-ready containment commands tailored to the incident context.
# Isolate compromised host via firewall (iptables)
sudo iptables -I FORWARD -s 10.0.1.42 -j DROP
sudo iptables -I FORWARD -d 10.0.1.42 -j DROP
sudo iptables -I INPUT -s 10.0.1.42 -j DROP
# Allow only IR team access for forensics
sudo iptables -I INPUT -s 10.0.1.42 -d 10.99.0.0/24 -j ACCEPT
# Block C2 domain at DNS level
echo "address=/malicious-c2.example.com/127.0.0.1" >> /etc/dnsmasq.d/ir-blocks.conf
sudo systemctl restart dnsmasq
# Disable compromised service account in Active Directory
Disable-ADAccount -Identity "svc_backup"
# Force password reset for potentially compromised accounts
Get-ADGroupMember "Domain Admins" | Set-ADUser -ChangePasswordAtLogon $true
# Revoke all active sessions for the compromised user
Revoke-AzureADUserAllRefreshToken -ObjectId (Get-AzureADUser `
-SearchString "svc_backup").ObjectId
Structure AI recommendations as scored options so the incident commander can make informed decisions quickly.
def recommend_containment(incident_data):
prompt = f"""Based on this active incident, recommend containment
strategies ranked by effectiveness and business impact.
INCIDENT SUMMARY:
- Type: {incident_data['type']}
- Affected systems: {incident_data['systems']}
- Current spread: {incident_data['spread_status']}
- Business-critical systems at risk: {incident_data['critical_assets']}
- Current business hours: {incident_data['is_business_hours']}
For each option provide:
| Option | Action | Effectiveness | Business Impact | Risk |
Also provide the exact commands/steps to execute each option."""
response = client.messages.create(
model="claude-sonnet-4-20250514",
max_tokens=2048,
messages=[{"role": "user", "content": prompt}]
)
return response.content[0].text
# Example output table from AI:
# | Option | Action | Effectiveness | Business Impact | Risk |
# |--------|---------------------------|---------------|-----------------|--------|
# | 1 | Isolate WS-042 + SRV-DB | High | High (DB down) | Low |
# | 2 | Block C2 IP at perimeter | Medium | None | Medium |
# | 3 | Disable svc_backup account | High | Medium | Low |
# | RECOMMENDED: Execute options 2 + 3 immediately, option 1 after backup |
Eradication removes the root cause of the incident. AI helps ensure nothing is missed by systematically checking for persistence mechanisms.
eradication_prompt = """Given the following incident details, generate
a comprehensive eradication checklist:
Attack type: Credential theft + lateral movement
Compromised accounts: svc_backup, jsmith
Malware found: Mimikatz (memory-resident), Cobalt Strike beacon
Affected systems: WS-042, SRV-DB-01
C2 infrastructure: 185.220.101.0/24
For each item, provide:
- Specific check to perform
- Command or tool to use
- How to verify successful eradication
- Common places attackers hide persistence"""
schtasks /query /fo LIST /vreg query HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\RunGet-WMIObject -Namespace root\subscription -Class __EventFilterGet-Service | Where-Object {$_.StartType -eq 'Automatic'}find / -name authorized_keys -type f 2>/dev/nullRecovery restores affected systems to normal operation. AI assists with verification procedures and monitoring for re-infection.
# AI-generated YARA rule for post-recovery monitoring
recovery_prompt = """Based on the IOCs from this incident, generate:
1. YARA rules to detect the malware variants observed
2. Sigma rules for the behavioral patterns identified
3. Network signatures (Snort/Suricata) for C2 communication
4. A 30-day enhanced monitoring plan
IOCs:
- File hash: a1b2c3d4e5f6... (Cobalt Strike beacon)
- C2 domains: update.legit-software[.]com, cdn.trusted-host[.]net
- User-Agent: Mozilla/5.0 (compatible; MSIE 10.0; Windows NT)
- Named pipe: \\.\pipe\msse-1234-server"""
Proper evidence handling can make or break a legal case. AI helps document everything meticulously while analysts focus on technical collection.
| Evidence ID | Type | Source | Collected By | Hash (SHA-256) | Time (UTC) |
|---|---|---|---|---|---|
| EV-001 | Memory dump | WS-042 | J. Analyst | a3f8c2...e91b | 15:02:33 |
| EV-002 | Disk image | WS-042 | J. Analyst | 7b2d41...f03a | 15:45:10 |
| EV-003 | Network PCAP | FW-Core | K. Engineer | d9e1a7...c44f | 15:12:08 |
| EV-004 | AD event logs | DC-01 | K. Engineer | 1f5e83...b27d | 15:20:55 |
| EV-005 | Malware sample | WS-042 | J. Analyst | c2a9f1...88e3 | 16:01:22 |
AI automatically logs every evidence interaction: who accessed it, when, what tools were used, and hash verification at each step. This creates a defensible audit trail.
AI provides the exact forensic collection commands and automatically documents each step with timestamps and hashes.
# Memory acquisition (Linux)
sudo dd if=/dev/mem of=/evidence/mem_dump_$(hostname)_$(date +%s).raw
sha256sum /evidence/mem_dump_*.raw >> /evidence/hashes.txt
# Network connections snapshot
ss -tunapeo > /evidence/netstat_$(date +%s).txt
ip route show > /evidence/routes_$(date +%s).txt
# Running processes with full details
ps auxef > /evidence/processes_$(date +%s).txt
ls -la /proc/*/exe 2>/dev/null > /evidence/proc_links_$(date +%s).txt
# Create forensic disk image with hash verification
sudo dc3dd if=/dev/sda of=/evidence/disk_image.dd \
hash=sha256 log=/evidence/dc3dd_log.txt
# Verify image integrity
sha256sum /evidence/disk_image.dd
# Compare against dc3dd output hash
AI drafts communication at each stage of the incident, ensuring consistent, professional messaging tailored to each audience.
Subject: [IR-2024-042] Active Security Incident - SEVERITY: CRITICAL
Status: Active - Containment in progress
Incident Commander: Sarah Chen
Bridge Line: +1-555-0142 / PIN: 8834
Summary: At 14:23 UTC, EDR detected credential theft activity on WS-042. Attacker has obtained svc_backup credentials and moved laterally to SRV-DB-01. Data exfiltration to external IP confirmed.
Immediate Actions Taken: C2 IP blocked at perimeter, svc_backup account disabled, WS-042 network-isolated.
Required: All domain admin accounts — verify your recent logon activity. Report any anomalies to IR bridge immediately.
Subject: Security Incident Briefing - Action Required
A security incident involving unauthorized access to an internal database server was detected today at 2:23 PM. The security team has contained the threat and is working to determine the full scope of impact. Customer-facing services remain operational.
Business impact: Internal database server temporarily offline for forensic analysis. Estimated restoration: 4-6 hours.
Customer impact: Under investigation. Preliminary analysis suggests customer PII may have been accessed.
Next update: 6:00 PM today or sooner if status changes.
Regulatory consideration: If PII exposure is confirmed, GDPR Article 33 requires notification to supervisory authority within 72 hours of becoming aware. AI should flag applicable notification deadlines based on data types and jurisdictions involved.
def generate_ir_communication(incident, audience, phase):
"""Generate audience-appropriate incident communications."""
prompt = f"""Draft an incident response communication for:
Audience: {audience} # "technical", "executive", "legal", "customers"
IR Phase: {phase} # "detection", "containment", "eradication", "recovery"
Incident Details:
- ID: {incident['id']}
- Type: {incident['type']}
- Severity: {incident['severity']}
- Affected systems: {incident['systems']}
- Data at risk: {incident['data_types']}
- Current status: {incident['status']}
- Business impact: {incident['business_impact']}
Guidelines:
- Technical audience: Include IOCs, affected systems, required actions
- Executive audience: Focus on business impact, timeline, decisions needed
- Legal audience: Include data types, jurisdictions, regulatory deadlines
- Customer audience: Transparent but measured, include protective steps
Use professional tone. Do not speculate beyond confirmed facts.
Include a "Next Update" timestamp."""
response = client.messages.create(
model="claude-sonnet-4-20250514",
max_tokens=1024,
messages=[{"role": "user", "content": prompt}]
)
return response.content[0].text
The most frequently skipped IR phase is also the most valuable. AI ensures thorough post-incident analysis by structuring the review process.
rca_prompt = """Perform a root cause analysis for this security incident.
Use the "5 Whys" technique and provide a fishbone (Ishikawa) diagram
structure.
INCIDENT TIMELINE:
{full_timeline}
ATTACK CHAIN:
1. Phishing email delivered to jsmith@corp.example.com
2. User clicked link, downloaded malicious macro document
3. Macro executed PowerShell downloader
4. Cobalt Strike beacon established C2 channel
5. Mimikatz extracted svc_backup credentials from memory
6. Lateral movement to SRV-DB-01 via SMB
7. Database export and exfiltration via HTTPS to external IP
Provide:
- Root cause identification (technical and process failures)
- Contributing factors
- Specific, actionable recommendations with priority
- Metrics to track improvement
- Detection gaps that allowed each step"""
AI applies structured analytical frameworks to produce actionable findings from incident data.
| Level | Question | Answer |
|---|---|---|
| Why 1 | Why was data exfiltrated? | Attacker had database access via svc_backup credentials |
| Why 2 | Why did the attacker have those credentials? | Mimikatz extracted them from WS-042 memory |
| Why 3 | Why were privileged credentials cached on a workstation? | svc_backup had interactive logon rights and was used for manual backup tasks |
| Why 4 | Why was a service account used interactively? | No PAM solution; team used shared credentials for convenience |
| Why 5 | Why was there no PAM solution? | PAM project was deprioritized in Q2 budget cycle |
Technical: Privileged service account with interactive logon rights cached on standard workstation. Process: Lack of privileged access management controls. Recommendation: Deploy PAM, enforce credential tiering, remove interactive logon for service accounts.
AI generates comprehensive post-incident reports that capture institutional knowledge and drive security improvements.
lessons_prompt = """Generate a Lessons Learned report for incident
IR-2024-042 using this structure:
1. EXECUTIVE SUMMARY (3-4 sentences)
2. INCIDENT METRICS
- Time to detect (TTD)
- Time to contain (TTC)
- Time to eradicate (TTE)
- Time to recover (TTR)
- Total incident duration
3. WHAT WENT WELL
4. WHAT NEEDS IMPROVEMENT
5. ACTION ITEMS (owner, priority, deadline)
6. DETECTION GAP ANALYSIS
7. UPDATED RISK ASSESSMENT
Incident data: {incident_full_record}
Timeline: {incident_timeline}
Team feedback: {team_survey_responses}
Format as a professional report suitable for CISO review."""
TTD: 7 minutes | TTC: 12 minutes | TTE: 4.5 hours | TTR: 18 hours | Total: 23 hours
Industry average for similar incidents without AI: TTD: 197 days. AI-assisted IR can compress timelines by orders of magnitude.
IR runbooks are step-by-step procedures for specific incident types. AI can generate, maintain, and improve runbooks based on lessons learned from actual incidents.
runbook:
name: "Ransomware Response"
version: 2.3
last_updated: "2024-11-15"
author: "IR Team + AI Assistant"
severity_default: "Critical"
triggers:
- "EDR alert: ransomware behavior detected"
- "Multiple file extension changes in short period"
- "Ransom note file detected (README.txt, DECRYPT_FILES.html)"
immediate_actions:
- step: "Isolate affected system from network"
command: "netsh advfirewall set allprofiles state on"
timeout: "30 seconds"
escalate_if_fails: true
- step: "Identify ransomware variant"
tool: "Upload sample to VirusTotal / ID Ransomware"
ai_assist: "Analyze ransom note and file extensions for variant ID"
- step: "Check for lateral spread indicators"
command: "Get-ADComputer -Filter * | Test-Connection -Count 1"
ai_assist: "Query SIEM for similar IOCs on other endpoints"
containment:
- step: "Block C2 at perimeter firewall"
- step: "Disable affected user accounts"
- step: "Snapshot affected VMs before further action"
def generate_runbook(incident_type, environment):
"""Generate a tailored IR runbook for a specific incident type."""
prompt = f"""Create a detailed IR runbook for: {incident_type}
Environment context:
{json.dumps(environment, indent=2)}
The runbook must include:
1. TRIGGERS - What alerts/events activate this runbook
2. SEVERITY CLASSIFICATION - How to determine initial severity
3. IMMEDIATE ACTIONS (first 15 minutes)
4. INVESTIGATION STEPS (with specific commands for our OS mix)
5. CONTAINMENT OPTIONS (ranked by impact)
6. ERADICATION CHECKLIST
7. RECOVERY PROCEDURES
8. COMMUNICATION TEMPLATES (by audience)
9. EVIDENCE COLLECTION REQUIREMENTS
10. POST-INCIDENT TASKS
For each step provide:
- Description of what to do and why
- Exact command(s) to execute
- Expected output / success criteria
- What to do if the step fails
- Escalation criteria
Format as YAML for integration with our SOAR platform."""
response = client.messages.create(
model="claude-sonnet-4-20250514",
max_tokens=4096,
messages=[{"role": "user", "content": prompt}]
)
return response.content[0].text
Build a library of AI-generated runbooks covering your most common and most critical incident types.
| Incident Type | Typical Severity | Key Containment Action | AI Value-Add |
|---|---|---|---|
| Ransomware | Critical | Network isolation | Variant ID, decryptor search |
| Phishing (credential theft) | High | Password reset, session revoke | Analyze phishing kit, find other victims |
| Insider threat | High | Account suspension | Behavioral analysis, data access audit |
| DDoS attack | High | Traffic filtering, CDN scaling | Traffic pattern analysis, source attribution |
| Supply chain compromise | Critical | Vendor isolation, dependency audit | Impact blast radius analysis |
| Data exfiltration | Critical | Egress blocking | Data classification, scope assessment |
| Cryptomining | Medium | Process termination | Identify entry point, check for persistence |
Practical architecture for embedding AI into your existing incident response tools and processes.
AI should be in the loop (providing recommendations) not on the loop (making autonomous decisions). All containment and eradication actions require human approval before execution.
A condensed example of an AI-generated IR playbook for a phishing incident with credential compromise.
playbook: phishing_credential_compromise
phase: identification
steps:
- action: "Extract IOCs from reported phishing email"
ai_prompt: |
Analyze this email header and body. Extract:
- Sender IP and domain (check SPF/DKIM/DMARC)
- All URLs (defang them)
- Attachment hashes
- Social engineering technique used
output: ioc_list
- action: "Search for other recipients"
command: |
# Exchange Online
Get-MessageTrace -SenderAddress "phish@evil.com" \
-StartDate (Get-Date).AddDays(-7) -EndDate (Get-Date)
ai_assist: "Analyze results to determine campaign scope"
- action: "Check for credential submission"
command: |
# Search proxy logs for phishing URL access
grep -i "evil-login-page.com" /var/log/proxy/access.log
ai_assist: "Identify users who visited the credential harvesting page"
- action: "Determine which users submitted credentials"
ai_prompt: |
Given proxy logs showing these users visited the phishing URL,
analyze POST request sizes to determine who likely submitted
credentials vs. who just loaded the page.
AI is a powerful tool but has critical limitations that must be understood during incident response.
You are the on-call SOC analyst. An active security incident has been detected. Use AI-assisted IR techniques to respond.
At 02:17 UTC, your SIEM fires multiple alerts. A workstation (WS-117, user: mwilliams) is exhibiting the following behaviors:
x8f2.update-service[.]xyz every 60 seconds (beaconing)Completeness (all IR phases addressed) | Technical accuracy (valid commands and techniques) | AI utilization (effective prompting) | Communication quality (audience-appropriate messaging) | Documentation (evidence handling and chain of custody)
Map each observed behavior to MITRE ATT&CK techniques to understand the full attack chain.
| Observed Behavior | MITRE Technique | Tactic |
|---|---|---|
| Base64-encoded PowerShell | T1059.001 | Execution |
| DNS beaconing to suspicious domain | T1071.004 | Command & Control |
| SMB connections to file servers | T1021.002 | Lateral Movement |
| Event log cleared | T1070.001 | Defense Evasion |
| Scheduled task persistence | T1053.005 | Persistence |
| Large file staging | T1074.001 | Collection |
The attacker is in the Collection / Exfiltration preparation stage. The 2.3 GB ZIP file indicates data staging before exfiltration. Containment is urgent — you may still prevent data leaving the network.
Lesson 09 will cover AI-Powered Threat Hunting — proactively searching for threats that evade automated detection using AI-driven hypothesis generation and investigation.