How to Respond to an AI Incident in 2026 | AI LLM Hacking Course Day 40 of 90

How to Respond to an AI Incident in 2026 | AI LLM Hacking Course Day 40 of 90
🤖 AI/LLM HACKING COURSE
FREE

Part of the AI/LLM Hacking Course — 90 Days

Day 40 of 90 · 44.4% complete

At 11pm, we discovered that the AI hadn’t crashed or been hacked in the usual sense. It had simply started helping a competitor.

For six hours, a major retailer’s recommendation engine had been confidently directing high-value customers toward a competitor’s products. The infrastructure was healthy. The model was running normally. There were no obvious network indicators, malware alerts, or compromised servers.

The problem was in the RAG knowledge base.

Four days earlier, a document had entered through the normal product data feed. Buried inside it was an indirect prompt injection that activated when customers queried a particular product category. The AI followed those instructions and produced convincing recommendations that looked perfectly normal to customers.

The investigation eventually led to the prompt-and-response logs. Those logs showed what the AI had been asked, what information it retrieved, and how its responses changed. Without them, reconstructing the incident would have been much harder.

This is the kind of incident I want you to be ready for in Day 40.

So far, we’ve focused on understanding AI attacks and putting controls around AI systems. Day 39 covered governance and compliance — the policies, responsibilities, and safeguards that should be in place before an incident occurs.

Today, I’m taking the next step: what do you actually do when those controls fail?

I’ll show you the way I approach an AI security incident from the moment something looks wrong. We’ll work through detection, triage, containment, evidence preservation, forensic investigation, recovery, and the lessons that need to come out of the incident.

The important difference is that AI incident response isn’t always about finding a compromised machine. Sometimes the infrastructure is perfectly healthy while the AI’s behavior has been manipulated somewhere inside the pipeline.

That means I have to investigate more than servers and network traffic. I need to look at prompts, retrieved documents, model behavior, tool calls, data pipelines, access records, and the logs that connect them.

That’s the real focus of Day 40: learning how to turn strange AI behavior into a structured security investigation — and then knowing what to do next.

By the end of this lesson, you should be able to answer three questions with confidence: What happened? What do I contain? And how do I recover safely?

🎯 What You’ll Master in Day 40

Recognise AI-specific incident detection signals that don’t appear in traditional SIEM alerting
Classify AI incidents by type to determine the appropriate response path
Apply graduated containment options that balance security response with business continuity
Collect the specific forensic evidence that AI incidents require
Execute eradication and recovery procedures for different AI compromise types
Build an AI incident response playbook and test it before you need it

⏱️ Day 40 · 3 exercises · Think Like Hacker + Kali Terminal + Kali Terminal

✅ Prerequisites

  • Day 35 — AI Security Automation

    — the production monitoring from Day 35 is the detection layer for Day 40; the logging infrastructure built in Day 35 is what makes Day 40’s forensics possible

  • Day 39 — AI Governance and Compliance

    — the governance framework from Day 39 includes incident notification obligations that Day 40’s response process must address

  • Python with logging and JSON capabilities — Exercise 2 builds the AI incident forensics collector

In Day 39, we looked at the governance side of AI security — including what your incident management process needs to look like before anything goes wrong. Today, in Day 40, I want to make that practical. If an AI security incident actually happens, what do I look at first, how do I contain it, what evidence do I preserve, and how do I recover without making things worse? That’s the operational incident response process we’ll work through here. Then, in Day 41, we turn the perspective around again and look at advanced red-team techniques — combining the skills from Days 1–40 to simulate more sophisticated, multi-stage attacks.


AI-Specific Incident Detection Signals

When I investigate a traditional breach, I usually have familiar things to look for: unusual network connections, unexpected file changes, suspicious authentication, new processes, privilege escalation, and other endpoint or network indicators. With an AI incident, I still check those things — but I don’t stop there. The infrastructure can look completely normal while the AI itself is behaving in a way it shouldn’t.

That’s the mindset I want you to develop here. Instead of asking only, “Is the server compromised?”, I also ask, “Is the AI behaving differently from its expected baseline?” I look for responses that contain information the user never requested, instructions that appear to have come from somewhere else, tool calls that don’t make sense for the request, sudden changes in how the model follows instructions, and unusual query patterns that look more like systematic probing than normal use.

For example, if a customer asks about a product and the model suddenly starts recommending a competitor that wasn’t mentioned anywhere in the conversation, that’s worth investigating. If an agent calls a sensitive tool even though nothing in the user’s request should have triggered it, that’s another signal. If the model suddenly starts revealing system-prompt content or returning credential-like strings, I treat that very differently from an ordinary bad response.

None of these signals should automatically be treated as proof of compromise. That’s important. A keyword match can produce false positives, and an unusual response can simply be a legitimate edge case. What I’m looking for is evidence that becomes meaningful when I correlate it with the rest of the AI activity.

This is where the production monitoring layer from Day 35 becomes useful. The logging and telemetry are already there; now I need detection rules that understand AI behaviour. Here are some practical starting rules I can build into that monitoring layer:

AI INCIDENT DETECTION RULES — MONITORING PATTERNS
# Detection rule 1: Possible system-prompt leakage
if any(keyword in response for keyword in SYSTEM_PROMPT_KEYWORDS):
alert(“SYSTEM_PROMPT_LEAKAGE”, severity=”HIGH”)
# Detection rule 2: Credential-like content in response
if re.search(r'(sk-|Bearer |API_KEY|password|secret)’, response, re.I):
alert(“CREDENTIAL_IN_RESPONSE”, severity=”CRITICAL”)
# Detection rule 3: Tool call outside the expected workflow
if tool_name not in EXPECTED_TOOLS_FOR_QUERY_TYPE(query):
alert(“UNEXPECTED_TOOL_INVOCATION”, severity=”HIGH”)
# Detection rule 4: Unexpected competitor mention
if COMPETITOR_NAMES_REGEX.search(response) and “competitor” not in query.lower():
alert(“ANOMALOUS_COMPETITOR_MENTION”, severity=”MEDIUM”)
# Detection rule 5: Possible prompt-injection attempt
INJECTION_PATTERNS = [“ignore previous”, “system:”, “new instructions”,
“jailbreak”, “ignore above”, “disregard”, “override”]
if any(p in query.lower() for p in INJECTION_PATTERNS):
alert(“INJECTION_ATTEMPT”, severity=”MEDIUM”)
# Detection rule 6: Unusual response-size increase
if len(response.split()) > BASELINE_MAX_TOKENS * 1.5:
alert(“RESPONSE_LENGTH_ANOMALY”, severity=”MEDIUM”)

One important point: I don’t rely on any single rule to declare an incident. A prompt containing “ignore previous instructions” might simply be a security researcher testing the application. A competitor mention might be legitimate. A long response might be expected for a particular workflow. The real detection value comes from correlation — what the user asked, what data was retrieved, what tools were called, what the model produced, and how that behaviour compares with the established baseline.

That shift — from looking only for compromised infrastructure to also looking for compromised behaviour — is one of the biggest differences between traditional incident response and AI incident response.


Incident Classification and Response Paths

Once I have enough evidence to believe something unusual is happening, I don’t immediately start changing things. First, I need to understand what kind of incident I’m dealing with. The classification matters because a prompt-injection attempt from a single user needs a very different response from a compromised RAG knowledge base that has already affected thousands of conversations.

I normally classify the incident along three dimensions: what was affected, how far the attacker got, and whether the attack is still active. That gives me a much clearer response path than simply labelling everything an “AI security incident.”

1. Attack Attempt — No Confirmed Impact

This is where I see evidence of an attack attempt, but I can’t yet demonstrate that the AI system was actually compromised. A user may submit a prompt-injection payload, probe for the system prompt, attempt to bypass a safety control, or send a sequence of jailbreak prompts.

My response here is usually investigation rather than emergency containment. I preserve the relevant prompts and responses, identify the account or session, check whether any tools were invoked, and look for similar activity from the same source. If the attempt was blocked and nothing else was affected, I don’t want to create unnecessary operational disruption.

2. Model Behaviour Anomaly — Possible Compromise

The next level is when the AI starts behaving differently from its established baseline. Maybe it suddenly reveals information it normally refuses to provide, follows instructions from retrieved content, calls tools in an unexpected sequence, or produces outputs that don’t match the application’s intended behaviour.

At this point, I treat the behaviour as a security signal rather than assuming it’s simply a model-quality problem. I compare the affected interactions with normal traffic, inspect the retrieved context, review recent changes, and check whether the behaviour can be reproduced.

3. Data or RAG Compromise

This is particularly important for production RAG systems. If malicious or manipulated content has entered the knowledge base, the attack can affect many users without the attacker ever touching the model infrastructure.

My response changes here. I identify the affected documents, ingestion job, source system, embeddings and retrieval path. I may temporarily remove the affected content from retrieval, quarantine the source, or disable the affected ingestion pipeline while preserving the original evidence for forensic analysis.

4. Tool or Agent Compromise

If an AI agent has access to email, databases, APIs, cloud resources or other tools, I treat unexpected tool activity much more seriously. The question is no longer just whether the model produced a bad answer. I need to determine whether the model actually caused an external action.

This is where I move quickly to contain the affected capability. Depending on the architecture, that might mean disabling a particular tool, revoking temporary credentials, restricting the agent’s permissions, or moving the workflow into a human-approval state.

5. Confirmed Security Incident

I classify an incident as confirmed when I have sufficient evidence that an attacker or malicious input caused an unauthorized change, disclosure, action, or security-control bypass. At that point, I’m no longer treating the event as an anomaly to investigate at my leisure. I’m in incident-response mode.

The priorities become straightforward: contain the attack, preserve evidence, determine scope, eradicate the cause, and recover safely. I also start recording decisions and timestamps because the investigation itself becomes part of the forensic record.

6. Business-Impact Incident

Sometimes the technical compromise is relatively small but the business impact is significant. An AI system might give incorrect financial advice, expose customer information, make unauthorized changes, or systematically provide misleading recommendations.

In those cases, I don’t let the technical team make the entire decision in isolation. Security, engineering, legal, compliance, privacy and the affected business owner may all need to be involved. The response path depends not only on how the AI was compromised, but on what the compromise actually did.

My rule of thumb: classify based on demonstrated impact, not how sophisticated the attack looks. A simple prompt injection that exposes customer data can be more serious than a sophisticated jailbreak that never escaped the test environment.

Choosing the Response Path

Once I’ve classified the incident, I choose the narrowest response that contains the risk without destroying evidence or unnecessarily taking the whole system offline.

Prompt-injection attempt: preserve the interaction, identify the source, investigate repetition and strengthen the relevant control.

Behaviour anomaly: compare against the baseline, trace the prompt and context chain, and determine whether the behaviour is reproducible.

RAG poisoning: quarantine the affected data and ingestion path, identify the scope of exposure, and rebuild or validate the affected retrieval layer.

Unexpected tool activity: restrict the affected tool or capability, review credentials and permissions, and determine exactly what actions were executed.

Confirmed compromise: activate the formal incident-response process, preserve evidence, contain the affected components, investigate the full attack path, and coordinate recovery.

The important thing is that I don’t use “take the AI offline” as my automatic answer. Sometimes that’s appropriate. Sometimes it creates more damage than the incident itself. If I can isolate a poisoned knowledge source, disable one tool, or place an agent behind human approval, I may be able to contain the incident while keeping the rest of the service operational.

That decision — what to isolate, what to leave running, and what evidence to preserve before making the change — is where AI incident response becomes a real operational discipline rather than just a checklist.


🧠 EXERCISE 1 — THINK LIKE A HACKER (20 MIN · NO TOOLS)
Tabletop an AI Security Incident from Alert to Resolution

⏱️ 20 minutes · No tools needed

Tabletop exercises reveal gaps in IR playbooks before a real incident exposes them. This exercise runs a realistic AI incident scenario from first alert through post-incident review — the complete response lifecycle.

SCENARIO: Monday 9:47am. The Day 35 production monitoring fires:
[CRITICAL] CREDENTIAL_IN_RESPONSE — 3 alerts in 4 minutes
[HIGH] UNEXPECTED_TOOL_INVOCATION — send_email fired without
explicit user request
[HIGH] INJECTION_ATTEMPT — 12 events in last 30 minutes from
the same user account

The AI is a customer service agent with tools:
– read_account (reads customer account data)
– send_email (sends email to customer’s registered address)
– create_ticket (creates support ticket)

Affected: the public-facing customer service AI.
Business impact: 4,000 customer interactions per hour.

WORK THROUGH THE INCIDENT:

MINUTE 0-5 (Triage):
What is your immediate assessment of what’s happening?
Which alert combination tells you this is active exploitation
rather than scanning/probing?

MINUTE 5-15 (Containment decision):
You have four options:
a) Rate limit the affected user account only
b) Disable the send_email tool system-wide
c) Fall back to a no-tool version of the AI
d) Full service shutdown
Which do you choose and why? What business stakeholders
do you notify at this point?

MINUTE 15-60 (Evidence collection):
List exactly what you collect, in what order, and why.
What’s the most time-sensitive evidence to preserve?

HOUR 1-4 (Eradication and root cause):
The credential found in responses appears to be a read-only
API key embedded in the system prompt — not customer data.
Does this change your severity assessment?
What root cause do you now suspect?
What needs to change before the service can be restored?

DAY 1 CLOSE (Post-incident):
What three things go into the post-incident report?
What changes to the test suite, monitoring, and governance
does this incident require?

✅ Triage answer: the combination of CREDENTIAL_IN_RESPONSE + UNEXPECTED_TOOL_INVOCATION + INJECTION_ATTEMPTS from the same account is active exploitation — the probing phase (INJECTION_ATTEMPTS) succeeded and transitioned to exploitation (tool invocation, credential leakage). Containment: (b) disable send_email tool system-wide — it’s the destructive action and disabling it restores safety without taking the service down; also block the specific account. Severity reassessment: a read-only API key in the system prompt is still High — it’s a system prompt leakage finding (LLM07) and depending on what that key accesses, potentially a credential exposure. Root cause: credentials should never be in system prompts — use environment variables. Post-incident: (1) regression test for system prompt credential patterns; (2) add monitoring rule for credential-format strings in responses; (3) governance: update AI deployment checklist to prohibit credentials in system prompts.

📸 Share your tabletop response timeline in #day40-incident-response on Comments.


Graduated Containment Options

When I confirm an AI security incident, my first instinct isn’t to shut down the entire AI system. Sometimes that’s necessary, but taking everything offline immediately can interrupt legitimate users, destroy useful runtime evidence, and make it harder to understand what the attacker was actually doing.

Instead, I use graduated containment. I start with the smallest action that can reliably stop the harmful behaviour, then escalate if I can’t control the incident at that level. The goal is simple: stop the attack without creating more damage than I need to.

Level 1 — Contain the Session or User

If the activity is isolated to one account, API key, conversation, or session, that’s where I start. I may terminate the session, temporarily restrict the account, revoke the affected API token, or prevent that identity from invoking sensitive AI capabilities.

Before I do that, I preserve what I can: the original prompt, complete conversation history, model response, timestamps, retrieved context, tool calls, session identifiers, authentication events, and relevant request metadata. I don’t want containment to erase the trail I’m about to investigate.

Level 2 — Disable the Affected Capability

Sometimes the user isn’t the real problem. The dangerous part may be one capability available to the model. If an agent is making suspicious database queries, for example, I may disable that database tool while leaving ordinary conversational functionality available.

The same principle applies to email actions, code execution, file access, web retrieval, payment functions, administrative APIs, and other privileged tools. If I can remove the capability that turns a malicious prompt into a real-world action, I’ve reduced the immediate risk without necessarily shutting down the whole application.

Level 3 — Isolate the RAG or Data Source

For a suspected RAG poisoning incident, I don’t immediately assume the model itself needs to be replaced. I trace which documents were retrieved, where they came from, when they were ingested, and what other queries may have retrieved the same content.

If I identify a suspicious source, I can quarantine that document, collection, connector, index partition, or ingestion pipeline. I then check whether related content entered through the same path. This is especially important because deleting one visible malicious document doesn’t tell me whether ten more were ingested in the same batch.

Containment isn’t eradication: removing a poisoned document from retrieval may stop the immediate behaviour, but it doesn’t explain how the document entered the system or whether other malicious content came through the same path. I treat those as separate investigation and eradication questions.

Level 4 — Restrict Model or Agent Permissions

If I can’t confidently identify one affected tool, I reduce what the AI is allowed to do. An autonomous agent might temporarily become read-only. High-impact actions might require human approval. External API access might be restricted. Service-account permissions might be reduced to the minimum required for investigation.

I find this particularly useful when I’m still determining scope. I may not yet understand the full attack path, but I can reduce the blast radius while the investigation continues.

Level 5 — Isolate the AI Component

If malicious behaviour continues across multiple users, data sources, or tools, I move containment outward. I may isolate the affected model endpoint, agent, orchestration service, vector store, plugin, connector, or application instance from the rest of the environment.

At this stage, I also become much more cautious about credentials. If the affected component had access to secrets or privileged tokens, I identify exactly which credentials were reachable and rotate or revoke those that I have reason to consider exposed. I don’t blindly rotate everything before preserving the relevant evidence and understanding the dependencies.

Level 6 — Full Service Shutdown

This is the option I reserve for incidents I can’t safely contain at a lower level. If sensitive data is actively leaking, unauthorized actions are continuing, the integrity of multiple AI components is uncertain, or I can’t determine the boundaries of the compromise, taking the affected service offline may be the safest decision.

At that point, availability becomes secondary to limiting further harm. But even here, I want the shutdown to be deliberate. Where practical, I preserve volatile evidence, active sessions, relevant logs, configuration state, model and prompt versions, retrieval records, and tool-execution history before changing the environment.

How I Decide How Far to Escalate

I base the containment level on impact, scope, confidence, and ongoing risk. Is customer data leaving the environment? Can the model execute external actions? Is the behaviour limited to one session or appearing across many users? Do I know where the malicious instruction entered the pipeline? And most importantly, is the harmful activity still happening?

If I can confidently isolate one poisoned document and stop the behaviour, I probably don’t need to shut down the entire AI platform. If I can’t tell whether the model, RAG layer, tools, credentials, or orchestration environment can still be trusted, I escalate.

GRADUATED AI INCIDENT CONTAINMENT
# Start narrow and escalate when containment is insufficient
LEVEL 1 → Isolate user / session / API key
LEVEL 2 → Disable affected tool or capability
LEVEL 3 → Quarantine RAG data source / ingestion path
LEVEL 4 → Reduce agent permissions / require human approval
LEVEL 5 → Isolate affected AI component or service
LEVEL 6 → Shut down the affected service
# Escalate immediately when:
→ Sensitive data is actively being exposed
→ Unauthorized external actions are continuing
→ Privileged credentials may be under attacker control
→ Multiple users or components are affected
→ The scope of compromise cannot be established

One thing I don’t want you to confuse is containment with recovery. If I disable a compromised tool and the suspicious behaviour stops, I’ve contained the immediate threat. I haven’t necessarily fixed the vulnerability, removed every malicious artifact, determined the full impact, or proved that the environment is safe to return to normal operation.

That’s why my containment question is deliberately narrow: “What can I isolate right now to stop further harm while preserving enough evidence to understand what happened?” Once I have that under control, I can move into deeper forensic investigation, eradication, and recovery.


AI Incident Forensics

Once I’ve contained the immediate problem, I don’t start deleting things and rebuilding the environment. First, I want to understand what actually happened. That’s where AI incident forensics becomes different from the traditional forensic process I’m used to.

In a conventional breach, I might spend a lot of time looking at disk artifacts, process execution, authentication events, network connections, and endpoint telemetry. I still want all of that for an AI incident, but it may not tell me why the AI started behaving differently. The most important evidence can be sitting inside the AI application’s own operational history.

So the first thing I want is the complete prompt-and-response trail for the incident window. I want to know what users asked, exactly what the model received, what it returned, when each interaction happened, and which session or request produced it. If the application uses RAG, I also want to know what documents were retrieved for each request. If the model can call tools, I want the corresponding tool-invocation records.

That last part is particularly important. A model response tells me what the AI said. A tool log can tell me what the AI actually did. If an agent sent an email, queried a database, modified a record, called an external API, or accessed a sensitive resource, I need evidence of that action independently of the model’s text response.

I also want to reconstruct the AI configuration as it existed during the incident. This means recording the model and deployment version, system-prompt version, safety configuration, tool definitions, application configuration, and relevant RAG state. A current configuration isn’t enough — I need to know what the system looked like when the suspicious behaviour occurred.

For a RAG incident, I go one step further. I want the document that was retrieved, its source, ingestion timestamp, document version or hash where available, embedding/index information, and the ingestion job that introduced it. I’m trying to answer a very specific question: did the attacker manipulate the AI at inference time, or had malicious content already entered the system before the incident began?

Think in timelines. I want to reconstruct the incident from before the first suspicious response through containment. When did the malicious content enter? When was it first retrieved? Which users received affected responses? Which tools were called? When did the behaviour stop? A timeline often tells me more than any individual log entry.

The Evidence I Want to Preserve

For a serious AI incident, I try to preserve the evidence before making changes that could overwrite it. At minimum, I’m looking for:

  • Prompt and response logs — the complete interaction history for the affected period.
  • Session and request identifiers — so I can connect individual interactions across services.
  • Retrieved context — the documents, chunks, metadata, and sources supplied to the model.
  • Tool invocation records — what tools were called, with what parameters, and what they returned.
  • Model and prompt versions — exactly what configuration produced the responses.
  • RAG and data-source state — what content was available to retrieval at the time.
  • Authentication and access logs — who accessed the AI components and data pipelines.
  • Application and infrastructure logs — supporting evidence that may establish how the attack entered or moved through the environment.

I don’t necessarily need every one of these to prove every incident. The point is to preserve enough evidence to reconstruct the attack path and establish scope before the normal operation of the system changes the evidence.

Why Configuration History Matters

One of the easiest mistakes to make is investigating the system as it exists today rather than the system that existed during the incident.

Imagine I discover suspicious responses on Monday and deploy a new system prompt on Tuesday. If I only examine Tuesday’s configuration, I may never understand why Monday’s responses were possible. The same problem occurs if the RAG index is rebuilt, a malicious document is deleted, or the model is upgraded before I capture the relevant state.

That’s why versioning matters. I want snapshots or immutable records of the configurations that were active during the incident window. Without them, I can identify that something went wrong without being able to confidently explain why.

Building the Incident Timeline

Once I’ve collected the evidence, I put it into a timeline. I start before the first known anomaly and work forward:

AI INCIDENT FORENSIC TIMELINE
T-4 days → Suspicious document enters product-data pipeline
T-3 days → Document indexed into RAG knowledge base
T+0 → First affected query retrieves malicious content
T+2 hrs → Behaviour anomaly begins appearing in responses
T+6 hrs → Security team identifies systematic behaviour
T+6 hrs → Affected data source is contained
T+6 hrs → Evidence preserved for investigation

The timeline lets me connect events that may look unrelated when viewed separately. A suspicious document four days earlier, a retrieval event this morning, an unusual response ten minutes later, and an unexpected tool call can become one coherent attack chain once I put them in chronological order.

And this is the point of AI forensics: I’m not just trying to prove that the AI produced a bad answer. I’m trying to reconstruct the chain of events that caused it — what entered the system, what the model received, what it produced, what actions followed, who was affected, and whether anything remains compromised.

Without that reconstruction, recovery is mostly guesswork. With it, I can move into eradication with a much better idea of what actually needs to be removed.


⚡ EXERCISE 2 — KALI TERMINAL (25 MIN)
Build the AI Incident Forensics Collector

⏱️ 25 minutes · Kali Linux · Python

This exercise builds the AI incident forensics collector — the tool that packages all AI-specific evidence into a structured forensics bundle when an incident is declared. Run it immediately after declaring an AI incident to preserve the evidence that deteriorates first.

Step 1: cd ~/ai-security-course && source venv/bin/activate
nano day40_forensics_collector.py

Step 2: Build the collector:

import os, json, hashlib, datetime, shutil
from pathlib import Path

def collect_ai_forensics(incident_id, incident_window_start, incident_window_end,
log_sources, model_config_path, rag_manifest_path):
“””
Collect and hash all AI incident forensic evidence into a structured bundle.
incident_window_start/end: ISO datetime strings
log_sources: dict of {log_name: log_file_path}
“””
bundle_dir = Path(f”forensics_{incident_id}_{datetime.datetime.now().strftime(‘%Y%m%d_%H%M%S’)}”)
bundle_dir.mkdir(exist_ok=True)
manifest = {
“incident_id”: incident_id,
“collection_time”: datetime.datetime.utcnow().isoformat() + “Z”,
“incident_window”: {“start”: incident_window_start, “end”: incident_window_end},
“evidence_items”: []
}

def add_evidence(name, source_path, evidence_type):
“””Copy evidence file, compute hash, add to manifest”””
if not Path(source_path).exists():
print(f” [MISSING] {name}: {source_path}”)
manifest[“evidence_items”].append({“name”: name, “status”: “MISSING”, “path”: source_path})
return
dest = bundle_dir / Path(source_path).name
shutil.copy2(source_path, dest)
sha256 = hashlib.sha256(Path(source_path).read_bytes()).hexdigest()
manifest[“evidence_items”].append({
“name”: name, “type”: evidence_type,
“source”: str(source_path), “collected_as”: str(dest),
“sha256”: sha256, “status”: “COLLECTED”
})
print(f” [OK] {name}: SHA256={sha256[:16]}…”)

# Collect all evidence types
print(f”\n=== AI INCIDENT FORENSICS — {incident_id} ===\n”)

# 1. Prompt-response logs (highest priority — may be rotated)
print(“Collecting prompt-response logs (highest priority):”)
for log_name, log_path in log_sources.items():
add_evidence(log_name, log_path, “prompt_response_log”)

# 2. Model configuration snapshot
print(“\nCollecting model configuration:”)
add_evidence(“model_config”, model_config_path, “model_configuration”)

# 3. RAG knowledge base manifest
print(“\nCollecting RAG state:”)
add_evidence(“rag_manifest”, rag_manifest_path, “rag_state”)

# 4. System prompt (create snapshot)
print(“\nCapturing system prompt state:”)
system_prompt_snapshot = {
“captured_at”: datetime.datetime.utcnow().isoformat(),
“note”: “Capture current system prompt from deployment configuration”
}
sp_path = bundle_dir / “system_prompt_snapshot.json”
sp_path.write_text(json.dumps(system_prompt_snapshot, indent=2))
manifest[“evidence_items”].append({“name”:”system_prompt”,”type”:”config_snapshot”,”status”:”COLLECTED”})

# Save manifest
manifest_path = bundle_dir / “forensics_manifest.json”
manifest_path.write_text(json.dumps(manifest, indent=2))

collected = sum(1 for e in manifest[“evidence_items”] if e.get(“status”)==”COLLECTED”)
missing = sum(1 for e in manifest[“evidence_items”] if e.get(“status”)==”MISSING”)
print(f”\nForensics bundle: {bundle_dir}”)
print(f”Collected: {collected} | Missing: {missing}”)
if missing:
print(“WARNING: Missing evidence items indicate logging gaps — see manifest for details”)
return str(bundle_dir)

# Test with simulated evidence paths
collect_ai_forensics(
incident_id=”INC-2026-0412″,
incident_window_start=”2026-05-12T09:40:00Z”,
incident_window_end=”2026-05-12T11:00:00Z”,
log_sources={
“chat_api_log”: “/tmp/chat_api.log”, # will show MISSING — ok for demo
“tool_invocation_log”: “/tmp/tools.log”,
},
model_config_path=”/tmp/model_config.json”,
rag_manifest_path=”/tmp/rag_manifest.json”
)

✅ You built the AI forensics collector that produces a structured, hashed evidence bundle with a manifest. The SHA-256 hash of each evidence item is the chain-of-custody record — it proves the evidence hasn’t been modified since collection. The MISSING status for items that don’t exist is the finding itself: missing prompt-response logs mean the incident window isn’t fully reconstructable, which is simultaneously a forensics gap and a monitoring gap that goes into the post-incident report. In a real incident, run this tool within the first 30 minutes — prompt-response logs are the first evidence to be rotated or overwritten.

📸 Screenshot your forensics bundle manifest output. Share in #day40-incident-response on Comments.


Eradication and Recovery

Once I know what happened and I’ve contained the incident, I can start removing the cause. This is where I have to be careful with AI systems because not every AI incident requires replacing the model. Before I rebuild anything, I want to answer one question: what was actually compromised?

If the incident was caused by an inference-time attack — for example, a prompt injection that exploited the way the application handled instructions — the model itself may be perfectly clean. In that situation, replacing the model doesn’t solve the underlying problem. I need to fix the configuration or application layer that allowed the attack to work.

That might mean correcting the system prompt, fixing the instruction-handling logic, tightening the affected input or retrieval path, removing poisoned RAG content, and rotating credentials if the attacker could have accessed them. I then test the corrected system against the original attack path to make sure the behaviour is actually gone.

The distinction becomes much more serious if I find evidence that the model itself has been compromised — for example, through poisoned fine-tuning data or malicious model weights. At that point, changing the system prompt isn’t enough. I need to replace the affected model with a version whose integrity I can verify.

If I have a known-good previous model version, rolling back is usually the fastest recovery option. But I don’t treat an older version as automatically safe. I still need to establish where the compromise came from and whether the same poisoned dataset, training pipeline, dependency, or deployment process could compromise the replacement again.

Don’t confuse rollback with eradication. Rolling back removes the compromised model version from production. It does not necessarily remove the attacker’s entry point. If the training or deployment pipeline is still compromised, I may simply recreate the same problem with the next model I deploy.

I Verify Before I Restore

One of the biggest mistakes I can make during recovery is being in a hurry to declare the incident over. The service may be responding normally again, but that doesn’t prove the environment is clean.

Before I return the system to normal operation, I verify the model or configuration against a known-good state, validate the RAG data and ingestion pipeline, check relevant credentials, review tool permissions, and rerun the attack scenarios that originally triggered the incident.

I also want to know whether the fix works outside the exact example I investigated. If one malicious document caused the incident, removing that document isn’t enough. I test whether another document containing the same type of instruction can produce the same behaviour. If a jailbreak worked against one prompt, I test variations rather than assuming that changing one keyword solved the problem.

Recovery Is a Controlled Return

I prefer to bring an affected AI service back gradually when the architecture allows it. That might mean starting with a restricted deployment, read-only tools, reduced permissions, limited traffic, or additional monitoring before restoring full functionality.

During this period, I’m watching closely for the behaviour that originally triggered the incident. If the system starts showing the same anomaly again, I want to catch it before the entire production environment is exposed.

The Supply Chain Has to Be Part of the Fix

This is especially important when the compromise involves model weights or training data. I can’t consider eradication complete simply because I’ve replaced one bad file.

I need to examine the path that produced and delivered that file: training datasets, fine-tuning jobs, model repositories, CI/CD pipelines, dependencies, access controls, artifact storage, and deployment processes. If the same attacker-controlled input can enter again, the next model may be compromised before it ever reaches production.

So my recovery checklist looks something like this:

AI ERADICATION & RECOVERY CHECK
1. Identify the compromised layer
2. Remove or quarantine the malicious artefact
3. Fix the vulnerability or attack path
4. Rotate exposed credentials and review permissions
5. Verify model, prompt, RAG and configuration integrity
6. Test the original attack and meaningful variations
7. Restore service gradually where possible
8. Monitor closely for recurrence
9. Validate the training / data / deployment supply chain

The rule I keep coming back to is simple: I don’t call an AI incident recovered just because the symptoms have disappeared. I call it recovered when I have reasonable evidence that the malicious artefact is gone, the entry point has been closed, the replacement components are trustworthy, and the same attack no longer produces the same result.

That’s the difference between restarting an AI service and actually recovering it.


The AI Incident Response Playbook

At this point, we’ve covered the individual pieces of AI incident response. Now I want to put them together into something I could actually use during an incident.

When an AI system starts behaving strangely, I don’t want to rely on memory or improvise the response while everyone is under pressure. I want a simple sequence that tells me what to establish first, what evidence to preserve, what I can safely change, and when it’s appropriate to bring the system back online.

The playbook below is the sequence I use as a mental model. The exact technical steps will depend on the architecture, but the order matters.

Phase 1 — Detect and Triage

First, I establish whether I’m looking at a genuine security incident or simply an application or model-quality problem. I start with the suspicious behaviour and work backwards.

  • Identify what changed and when it first appeared.
  • Compare the behaviour with the established baseline.
  • Identify affected users, sessions, models, tools and data sources.
  • Check whether the behaviour is still occurring.
  • Assign an initial severity based on actual impact and exposure.

I don’t need the complete root cause at this stage. I need enough confidence to decide whether I have to contain something immediately.

Phase 2 — Preserve Evidence

Before making changes, I preserve the evidence that could disappear when the system changes. That includes prompt and response logs, retrieved context, tool calls, authentication records, configuration versions, model versions, RAG state, and relevant infrastructure telemetry.

I also establish the incident timeline. When did the suspicious content enter? When was it first retrieved? When did the behaviour begin? Which users were affected? What actions did the AI take? What happened immediately before containment?

If I can’t reconstruct the timeline later, I’ve probably lost something important during the response.

Phase 3 — Contain

Next, I stop the active risk. I start as narrowly as possible and escalate when necessary.

  • Restrict the affected user, session or API key.
  • Disable the affected tool or capability.
  • Quarantine suspicious RAG content or an ingestion source.
  • Reduce agent permissions or require human approval.
  • Isolate the affected AI component.
  • Take the service offline if the risk cannot be safely contained another way.

The important thing is that I don’t confuse stopping the behaviour with fixing the incident. Containment buys me time. The investigation still has to explain what happened and whether anything else was affected.

Phase 4 — Investigate

Once the immediate risk is controlled, I follow the attack through the AI pipeline. I want to know where the malicious instruction or data entered, how it reached the model, what the model did with it, and whether that behaviour produced any external impact.

For a RAG incident, that means tracing the document through ingestion, indexing and retrieval. For an agent incident, I trace the tool calls and permissions. For a model compromise, I investigate the model artifact, training or fine-tuning pipeline and deployment history.

At this stage, I’m also trying to establish scope. One affected conversation is very different from six hours of affected customer interactions, and both are different from a compromised model being deployed across the entire organization.

Phase 5 — Eradicate

Now I remove the actual cause rather than just the visible symptom.

If it was an application or prompt-injection weakness, I fix that weakness. If malicious RAG content entered the system, I remove it and investigate the ingestion path. If credentials were exposed, I rotate them and review their permissions. If the model artifact itself was compromised, I replace it with a verified version and investigate the supply chain that produced it.

I also ask one uncomfortable question here: could the attacker do the same thing again? If the answer is yes, I haven’t finished eradication.

Phase 6 — Recover Carefully

I don’t immediately switch everything back to normal. Where the architecture allows it, I restore the service gradually and keep additional monitoring in place.

I validate the model and configuration, test the original attack path, verify the RAG sources, check tool permissions, and watch for the same behavioural indicators that triggered the incident.

If the system passes those checks, I can progressively restore normal functionality. If the suspicious behaviour returns, I stop the recovery and go back to investigation.

Phase 7 — Close the Incident

The incident isn’t finished when the application is back online. I still need to document what happened, what was affected, what evidence supports the conclusions, which controls failed, and what needs to change.

This is also where the governance work from Day 39 becomes practical again. The incident record, regulatory assessment, control changes, ownership and follow-up actions all need to feed back into the organization’s broader AI risk-management process.

AI INCIDENT RESPONSE — QUICK PLAYBOOK
# 1. DETECT
Identify abnormal AI behaviour and establish the incident window
# 2. PRESERVE
Capture prompts, responses, RAG context, tool calls and configuration state
# 3. CONTAIN
Stop the active risk using the narrowest effective containment
# 4. INVESTIGATE
Trace the attack path and establish scope and impact
# 5. ERADICATE
Remove the malicious artefact and close the entry point
# 6. RECOVER
Restore from a verified state and validate the original attack path
# 7. LEARN
Document root cause, impact, control failures and corrective actions

That’s the playbook I want you to remember: detect, preserve, contain, investigate, eradicate, recover, and learn.

The order isn’t arbitrary. If I contain before preserving critical evidence, I may lose part of the attack trail. If I eradicate before understanding the root cause, I may remove the obvious malicious artefact while leaving the entry point open. And if I recover without testing the original attack path, I may simply put the same vulnerability back into production.

Good AI incident response isn’t about reacting quickly and changing everything. It’s about moving quickly without losing control of the investigation.


⚡ EXERCISE 3 — KALI TERMINAL (15 MIN)
Build the AI Incident Response Playbook Generator

⏱️ 15 minutes · Kali Linux · Python

This exercise builds the AI IR playbook generator — producing incident-type-specific response checklists that an on-call engineer can follow under pressure at 2am without having to remember the methodology from a course they did six months ago.

Step 1: nano day40_ir_playbook.py

PLAYBOOKS = {
“injection_active”: {
“title”: “Active Injection Attack”,
“detection_signals”: [“INJECTION_ATTEMPT alerts”, “anomalous tool invocations”,
“output content deviating from baseline”],
“immediate_actions”: [
“Block specific user account/IP triggering alerts”,
“Rate limit affected endpoint to reduce attack velocity”,
“Disable tool integrations if tool hijacking is confirmed”,
“Preserve prompt-response logs — do not rotate”,
],
“evidence_to_collect”: [
“Complete prompt-response log for incident window”,
“Tool invocation log for incident window”,
“System prompt current version and hash”,
“Attacker’s user account details and session history”,
],
“eradication_steps”: [
“Identify and patch system prompt injection surface”,
“Rotate any credentials exposed in responses”,
“Add regression test for the specific technique used”,
“Update monitoring rules with attacker’s input patterns”,
],
“recovery_criteria”: [
“Injection technique blocked in regression test suite”,
“No credential patterns in response sample”,
“Tool invocations returning to baseline rate”,
]
},
“rag_poisoning”: {
“title”: “RAG Knowledge Base Poisoning”,
“detection_signals”: [“Anomalous content in AI responses”,
“References to entities not in user query”,
“Competitor mentions, policy violations in outputs”],
“immediate_actions”: [
“Identify and quarantine the poisoned document”,
“Disable document ingestion pipeline to prevent further poisoning”,
“Roll back RAG knowledge base to last known-good state if available”,
],
“evidence_to_collect”: [
“The poisoned document with full ingestion timestamp”,
“All responses generated while poisoned document was in index”,
“Document ingestion pipeline logs showing source of poisoned doc”,
“RAG retrieval logs showing which queries triggered the poisoned document”,
],
“eradication_steps”: [
“Remove poisoned document from vector store”,
“Re-index knowledge base from known-clean source”,
“Add content scanning to document ingestion pipeline”,
“Identify and notify users who received poisoned responses”,
],
“recovery_criteria”: [
“Poisoned document removed and re-indexing complete”,
“Ingestion pipeline has content scanning enabled”,
“Baseline content quality restored in test queries”,
]
}
}

def generate_playbook(incident_type):
pb = PLAYBOOKS.get(incident_type)
if not pb:
print(f”No playbook for type: {incident_type}”)
return
print(f”\n{‘=’*60}”)
print(f”AI IR PLAYBOOK — {pb[‘title’].upper()}”)
print(f”{‘=’*60}”)
for section, items in pb.items():
if section == “title”: continue
print(f”\n{section.replace(‘_’,’ ‘).upper()}:”)
for item in items:
print(f” ☐ {item}”)
print()

generate_playbook(“injection_active”)
generate_playbook(“rag_poisoning”)

✅ You built the AI IR playbook generator that produces incident-type-specific checklists. The checkbox format is deliberate — under incident pressure, engineers need to know what’s been done and what hasn’t. A narrative playbook gets skipped. A checkbox list gets completed. Extend this generator with playbooks for model compromise, data exfiltration confirmed, and DoS attack — one playbook per incident type from the classification taxonomy. Post the generated playbooks in your team’s runbook system before you need them, not when you need them.

📸 Screenshot your generated playbook output. Share in #day40-incident-response on Comments. Tag #day40complete

📋 AI Incident Response — Day 40 Reference Card

AI detection signalsOutput content deviation · unexpected tool calls · credential patterns · injection keywords in input
No network IOCsAI incidents don’t appear in network captures — evidence lives in prompt-response logs
First containment choiceDisable specific tool integrations — preserves service, stops destructive actions
Evidence priority 1Prompt-response logs — collect immediately, may be rotated within hours
Evidence priority 2Model version + system prompt + RAG state at time of incident
Eradication: injectionPatch system prompt surface + rotate exposed credentials + add regression test
Eradication: RAG poisonRemove poisoned doc + re-index + add ingestion content scanning
Eradication: model compromiseRoll back to prior version OR retrain — verify integrity of rollback target first
Post-incident outputRegression test + monitoring rule update + governance policy update
IR tools~/ai-security-course/day40_forensics_collector.py · day40_ir_playbook.py

✅ Day 40 Complete — AI Incident Response

AI-specific detection signals, incident classification and response paths, graduated containment that balances security with business continuity, AI incident forensics including evidence priority and chain-of-custody, eradication matched to compromise type, the IR playbook generator, and the complete evidence collection framework. Day 41 opens the advanced phase — sophisticated multi-technique attack chains that combine everything from Days 1–40 into the kind of adversary behaviour that real-world threat actors use against production AI deployments.


🧠 Day 40 Check

During an AI incident investigation, you find that the prompt-response logs for the incident window were automatically rotated two hours after the incident occurred, before the IR team collected them. What is the impact on the investigation and what process change does this require?



AI Incident Response FAQ

How is AI incident response different from traditional IR?
Three key differences: Detection — AI attacks produce output anomalies and unexpected tool calls rather than network IOCs. Forensics — evidence lives in prompt-response logs and model configuration records, not in network captures or file system artefacts. Eradication — AI compromise may be in model weights or RAG knowledge base, requiring model rollback or retraining rather than file restoration.
What logs are needed for AI incident forensics?
Complete prompt-response logs for the incident window, model version and configuration at time of incident, tool invocation logs showing what external actions the AI triggered, RAG knowledge base state, agent memory state if applicable, and API gateway logs for request patterns. Many organisations discover their logging is inadequate at the point of incident — build the infrastructure before you need it.
What are the containment options for an active AI injection attack?
Graduated options: (1) block the specific user account; (2) disable specific tool integrations to limit blast radius while keeping the service live; (3) rate limit to reduce attack velocity; (4) fall back to a no-tool model version as degraded service; (5) full service isolation when data exfiltration or destructive tool use is confirmed. Choose based on business criticality and confirmed impact.
← Previous

Day 39 — AI Governance and Compliance

Next →

Day 41 — Advanced Red Team Techniques

📚 Further Reading

  • Day 41 — Advanced Red Team Techniques — The offensive techniques that Day 40’s IR playbooks are designed to detect and contain — understanding the attacker’s methodology makes the defender’s response more effective.
  • Day 35 — AI Security Automation — The production monitoring infrastructure that feeds Day 40’s detection rules — the logging foundation that makes AI incident forensics possible.
  • CISA Incident Response Playbooks — CISA’s IR playbook framework — the traditional IR structure that Day 40’s AI-specific procedures extend and adapt.
Mr Elite
The retailer’s incident resolved cleanly because one engineer had set up comprehensive logging six months earlier for a performance investigation that was long since closed. The logs were there because of a coincidence — not because the team had thought “we’ll need these for incident response.” The forensics collector, the log retention policy, the IR playbook — all of those were built after the incident as part of the post-incident review. They should have been built before. The cost of building them before is a few hours of engineering time and a storage bill. The cost of not having them when you need them is an incident investigation that can only establish partial root cause, a regulatory notification that has to say “we cannot determine the full scope of the exposure,” and the probability that the same technique will be used again before you’ve confirmed you’ve closed the right gap.

Join free to earn XP for reading this article Track your progress, build streaks and compete on the leaderboard.
Join Free
Lokesh N. Singh aka Mr Elite
Lokesh N. Singh aka Mr Elite
Founder, Securityelites · AI Red Team Educator
Founder of Securityelites and creator of the SE-ARTCP credential. Working penetration tester focused on AI red team, prompt injection research, and LLM security education.
About Lokesh ->

Leave a Comment

Your email address will not be published. Required fields are marked *