Courses3 levels
Level 1 · Foundations11 courses
Level 2 · Core5 courses
Level 3 · Advanced5 courses
Labs8 topics
Library Practice exams AI Range Pricing Start free

Lesson 02 · 45 minutes

Detect injection and abuse in the logs

After this lesson you can
  • Write four detection rules that read only the log file
  • Combine the rules into a score and count the alerts on a quiet week and on a week with trouble
  • Reduce false alerts and say what each rule cannot see
Lab files of this lesson (8)

The lab folder as it stands after this lesson. Unzip it in ~/krlab.

More

The zip holds every file that the course has printed up to here. To start this lesson with the files of the earlier lessons only, take the zip of the lesson before. Type the code yourself first: you learn more.

Scenario

The security lead of Orbit Parcels asks: "Did anyone attack Orbi last week, and would we have known on the day?" You have the log of week 2 and no other source. Week 1 was quiet, so every alert in week 1 is a false alert. You write rules, count what they find, and tune them until week 1 is silent and week 2 still shows the attacks.

Recall

Lesson 1: why can a rule read an excerpt of 60 characters but not the whole prompt?

The record keeps only the first 60 characters after sanitising, and only for 7 days. A rule that needs more text cannot run on this log. You choose rules that work with the fields that you are willing to store.

Lesson 1: what does the prefix `ext-` in a document id mean?

The document came from outside: an inbound email or a web page. Its text is untrusted. The prefix kb- marks a document that the company wrote.

The idea

A rule is a function that reads one record and says yes or no. A rule that fires is not yet an alert: each one has a way to be wrong, and a person must read every alert. So each rule gets a weight, the weights of the rules that fire are added, and an alert needs a score of 2 or more.

RuleIt fires whenWeightA normal case that also fires it
Known phraseThe excerpt holds a phrase from a list of known attack phrases1A customer asks what "ignore previous instructions" means
Long textThe prompt or the response is over 1,500 characters1A customer pastes a long letter
Tool after untrusted contentA tool that acts ran in a request that read an ext- document2An employee asks for a summary and an email
Refusal rateOne user sent 5 requests or more in a day and half were refusedper user-dayA user who asks many off-topic questions

The first three are about injection: direct injection (a user writes the attack) and indirect injection (the attack hides in a document), as in "Securing LLM applications" (lesson 2). It is risk LLM01 in the OWASP Top 10 for LLM Applications (2025). The tool rule is the one from "Securing AI agents and MCP" (lesson 3) turned into a detector: it sees the misuse, not the hidden text, which the log does not hold. The fourth rule is about a user who probes.

From a record to an alert
RecordRulesScoreAlertRevieweach rule says yes or noadd the weights2 or more raises an alerta person reads itRecordRulesScoreAlertReview1234
  1. Record → Rules: each rule says yes or no
  2. Rules → Score: add the weights
  3. Score → Alert: 2 or more raises an alert
  4. Alert → Review: a person reads it

Worked example

1. Count the ingredients

Count, for each week, the records that a rule could use.

python3 -c "
from logrec import load
for w in ('week1', 'week2'):
    rs = load(f'logs/{w}.jsonl')
    print(w, len(rs), 'records,', sum(any(d.startswith('ext-') for d in r['docs']) for r in rs), 'read an ext- document,', sum(r['decision'] == 'refused' for r in rs), 'refused')
"
week1 908 records, 34 read an ext- document, 12 refused
week2 1399 records, 32 read an ext- document, 17 refused

2. Write the rules

detect.py holds the four rules. any(...) is true when at least one item of a list is true. A set ({...}) is a group of values without order: WIDE and NARROW are two sets of tool names. collections.Counter counts how often each value appears. WIDE holds every tool that does something. NARROW holds only the tools whose effect leaves the building: a refund and an email to an outside address. defaultdict is a dictionary that makes a missing entry by itself.

detect.py

"""detect.py: rules over the log. A record rule returns True or False. A user rule returns (user, day) pairs."""
from collections import Counter, defaultdict

PHRASES = ["ignore previous instructions", "ignore all previous", "disregard the rules", "you are now",
           "developer mode", "print your system prompt", "repeat everything above"]
LONG_CHARS = 1500
WIDE = {"issue_refund", "send_email_internal", "send_email_external"}     # every tool that does something
NARROW = {"issue_refund", "send_email_external"}                          # only tools whose effect leaves the building
WEIGHT = {"phrase": 1, "length": 1, "tool": 2}
ALERT_AT = 2


def phrase(r):
    return any(p in r["excerpt"].lower() for p in PHRASES)


def length(r):
    return r["prompt_len"] > LONG_CHARS or r["resp_len"] > LONG_CHARS


def tool(r, actions=NARROW):
    """An action tool ran in a request that read untrusted content (a document id that starts with ext-)."""
    return any(d.startswith("ext-") for d in r["docs"]) and any(t in actions for t in r["tools"])


def score(r, actions=NARROW):
    hits = {"phrase": phrase(r), "length": length(r), "tool": tool(r, actions)}
    return sum(WEIGHT[k] for k, v in hits.items() if v)


def record_alerts(records, actions=NARROW):
    """Ids of the records whose score reaches ALERT_AT."""
    return [r["id"] for r in records if score(r, actions) >= ALERT_AT]


def refusal_alerts(records, min_requests=5, rate=0.5):
    """(user, day) pairs with at least min_requests requests of which at least `rate` were refused."""
    seen = defaultdict(Counter)
    for r in records:
        key = (r["user"], r["ts"][:10])
        seen[key]["all"] += 1
        seen[key]["refused"] += r["decision"] == "refused"
    return sorted(k for k, c in seen.items() if c["all"] >= min_requests and c["refused"] / c["all"] >= rate)

3. Count what each rule finds

run_detect.py runs each rule on both weeks and checks week 2 against the truth file that the generator wrote. A lambda is a small function without a name. Between two sets, & gives the items that are in both and - gives the items that are only in the first. Save the file and run it.

run_detect.py

"""run_detect.py: count what each rule finds in the two weeks, and check week 2 against the truth file."""
import json

import detect
from logrec import load

week1, week2 = load("logs/week1.jsonl"), load("logs/week2.jsonl")
truth = json.load(open("logs/truth-week2.json"))

print(f"{'rule':28}{'week 1':>8}{'week 2':>8}")
for name, rule in [("known phrase", detect.phrase), ("long text", detect.length),
                   ("tool after ext, wide set", lambda r: detect.tool(r, detect.WIDE)),
                   ("tool after ext, narrow set", detect.tool)]:
    print(f"{name:28}{sum(map(rule, week1)):8}{sum(map(rule, week2)):8}")
print(f"{'score >= 2 (alerts)':28}{len(detect.record_alerts(week1)):8}{len(detect.record_alerts(week2)):8}")
print(f"{'refusal rate (user-days)':28}{len(detect.refusal_alerts(week1)):8}{len(detect.refusal_alerts(week2)):8}")

alerts, bad = set(detect.record_alerts(week2)), set(truth["incident_records"])
print("week 2 alerts:", sorted(alerts))
print(f"true alerts {len(alerts & bad)}, false alerts {len(alerts - bad)}, missed {len(bad - alerts)}")
print("refusal alerts:", detect.refusal_alerts(week2))
python3 run_detect.py
rule                          week 1  week 2
known phrase                       1       9
long text                         10     158
tool after ext, wide set          21      19
tool after ext, narrow set         0       2
score >= 2 (alerts)                0       4
refusal rate (user-days)           0       1
week 2 alerts: ['r200062', 'r200681', 'r200741', 'r201277']
true alerts 4, false alerts 0, missed 0
refusal alerts: [('u_12cfc228', '2026-10-16')]

Read the table from the top. The phrase rule has one hit in the quiet week: a customer asked about the phrase. The length rule has hits in week 1 too, from pasted letters. The wide tool rule has 21 hits in week 1: ordinary employees asked for a summary and an internal email. A rule list that alerts on each of them would drown you. The narrow tool rule has 0 hits in week 1 and 2 hits in week 2.

Hits of each rule in the quiet week 1
Known phrase1Long text10Tool after ext, wide set21Tool after ext, narrow set0Score of 2 or more0Known phrase1Long text10Tool after ext, wide set21Tool after ext, narrow set0Score of 2 or more0

The combined score gives 0 alerts in week 1 and 4 in week 2. The truth file says that week 2 holds 4 records that did harm or could have, and the rules find all 4 with no false alert. This score is a lab result: you tuned the rules and the narrow tool set on these two weeks, and then scored them on the same weeks. The fair test is a week that you have not seen: week 3 of the scenario test. The aim that holds in real work is the quiet week, with no false alert. The refusal rule finds one user-day in week 2, and none in week 1.

4. Read the quiet-week hits

Do not trust a count that you have not read. Print the week-1 hits of the phrase rule and of the length rule.

python3 -c "
import detect
from logrec import load
for r in load('logs/week1.jsonl'):
    if detect.phrase(r) or detect.length(r):
        print(r['id'], 'phrase' if detect.phrase(r) else 'length', r['prompt_len'], r['excerpt'][:45])
"
r100049 length 1821 Please read this letter from a customer and d
r100246 phrase 71 What does 'ignore previous instructions' mean
r100252 length 1600 Please read this letter from a customer and d
r100509 length 1912 Please read this letter from a customer and d
r100604 length 2107 Please read this letter from a customer and d
r100729 length 1818 Please read this letter from a customer and d
r100735 length 1675 Please read this letter from a customer and d
r100798 length 1797 Please read this letter from a customer and d
r100854 length 2126 Please read this letter from a customer and d
r100860 length 2107 Please read this letter from a customer and d
r100885 length 2103 Please read this letter from a customer and d
A quiet-week hit of the phrase rule
r100246the recordphrasethe rule that fired71length of the promptWhat does 'ignore previous instructions' meana normal questionr100246the recordphrasethe rule that fired71length of the promptWhat does 'ignore previousinstructions' meana normal question

Each hit is a normal request. The phrase is in the middle of a question, and the long texts are letters that a clerk pasted. Neither one is an attack, and neither alone reaches the score of 2.

5. See what the score misses

The score keeps week 1 silent. It also hides the attempts that failed. List the records of week 2 with a score of exactly 1 and a refused decision.

python3 -c "
import detect
from logrec import load
rs = [r for r in load('logs/week2.jsonl') if detect.score(r) == 1 and r['decision'] == 'refused']
print(len(rs), 'refused attempts with a score of 1')
print(sorted({r['user'] for r in rs}))
print(detect.refusal_alerts(load('logs/week2.jsonl')))
"
6 refused attempts with a score of 1
['u_12cfc228']
[('u_12cfc228', '2026-10-16')]

Six attempts were refused, and one user sent all of them. The record rule did not alert on them, but the refusal-rate rule did, on the user-day. The two kinds of alert cover different things: a record alert says "read this request", and a user alert says "look at this person's day". The refused attempts did no harm. The seventh record of this user, a long answer after the phrase "repeat everything above", is one of the four true alerts.

Your turn

Files you need: logrec.py, detect.py, run_detect.py and the data of lesson 0 (kr-lab.sh for this lesson, then python3 makelogs.py). Work on a copy of detect.py and make two changes. Add the phrase system prompt to PHRASES, because a customer who asks for it is probing. Lower LONG_CHARS to 2000, so that the shorter pasted letters no longer fire the rule. Run both weeks again.

Decide for yourself, and write down, whether each change was worth it: what did it add, and what did it break? The page checks only the counts.

Check yourself

The tool rule fired 21 times in week 1 with the wide set. Why did you move to the narrow set and not drop the rule?

The rule is the only one that sees the indirect injection, which hides in a document. The wide set mixed in tools whose effect stays inside the company. The narrow set keeps the tools whose effect leaves it: a refund and an outside email. Fewer false alerts, and the harm that matters is still seen.

An attacker reads this lesson. Name one way around each of the first three rules.

The phrase list: write the attack in other words or another language, or put it after the first 60 characters, which are the only ones in the log. The length rule: keep the text short. The tool rule: make the attack use an internal email, which the narrow set ignores. No rule is a wall. That is why you keep several, test them on replayed attacks, and treat each rule as a reason to look.

Why is a quiet week with 0 alerts a better test than a week with trouble?

A rule is judged by two numbers: how many real events it finds and how many normal events it flags. The quiet week measures the second number without any doubt, because every alert is a false alert. A busy week mixes the two and you need a truth file for it.

What does the refusal rule see that the record rules do not?

A pattern across records. One refused request means nothing. Six refused requests in one afternoon from one user is a person who is testing the limits. The rule groups the records by user and by day before it decides.

Field notes

  • Log which rule fired and which version of the rules was used, next to every alert. When a rule changes, the old alerts must still be understood. The rules read the excerpt, which lives 7 days (lesson 1), so run them in that time and keep the alerts.
  • Replay old attacks through the rules every time you change them. A rule that never fires is untested, not safe. Keep your own decoys, such as the pasted letter, in the test set too. A refused attempt is a signal, not an incident: keep it for the trend, because a user who tries six times today may try something new tomorrow.
  • The log shows the effect (a tool ran after an ext- document), not the hidden text. That is enough to act on. For the text, you would need to store the document under its own access rules, with a short life.
  • Weights are a judgement. Review them when the false-alert rate changes, and tell the reviewers what the score means.
  • To run a rule in a SIEM, write it as a Sigma rule ("Security operations basics", lesson 7). The tool rule becomes a detection block: docs|startswith: 'ext-' and tools: send_email_external, over a logsource that you name for the Orbi log. The field names are those of lesson 1, so change them only with a new version of the record.