Lesson 06 · 45 minutes
Answer threat questions from an intel base and check every source
- Retrieve the reports that match a question and show their sources
- Check that every claim in an answer names a source file that supports it
- Find stale, conflicting and unverified reports before an answer uses them
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 SOC keeps ten short threat reports from partners and from its own analysts. When an alert names a group, the analyst asks the intel base a question such as "Which port does Group Alder use?". A colleague wired a model to the base. Last week it answered with a port that no report holds, and with the name of a report that does not exist. Your lead asks: "Make the base answer with its sources, and make code reject any answer that does not. Then tell me which reports I should not trust." The reports and groups are invented.
Recall
Lesson 5: why did recall fall when the wording of the messages changed?
The model had learned old words, and the new messages used others. The data had shifted. Facts that do not depend on wording lasted longer.
Lesson 3: who decides whether a summary keeps the key facts, the model or the code?
The code. The checker compares the text with facts that code found, and the model only drafts. The same rule holds here: the check of a source is done by code.
The idea
Retrieval means that the system first finds the reports that match the question, and only then writes an answer from them. Lesson 6 of "How LLMs and agents work" calls this RAG (retrieval-augmented generation). It lowers the invention of facts, and it does not remove it. A model can still cite a report that does not say what the model claims. So every claim in an answer carries a source, the name of a report file, and code checks it.
- Analyst → Search: Which port does Group Alder use?
- Search → Reports: find the closest reports
- Reports → Model: the model writes claims from them
- Model → Checker: each claim carries a source
- Checker → Reports: file exists, claim is in it
- Checker → Analyst: the answer, with its warnings
Three things make a report unsafe even when the check passes.
| Problem | Meaning | Test in this lesson |
|---|---|---|
| Stale | Older than the limit (180 days here). Attackers change tools, ports and addresses. | The date against a fixed day, 2026-11-01 |
| Conflict | Two reports give different values for the same claim. | The same key with two values |
| Unverified | The source has no record of being right, for example a forum post. | The word in the source line |
Retrieval can fetch an old report first, because it is a good text match. Match is not trust. The answer must carry the warnings.
Worked example
1. Write the reports
gen.py intel writes the ten reports into the folder intel/. Each has a date, a source, a short text and a list of claims in the form key = value.
python3 gen.py intel
cat intel/rpt-07.txtwrote 10 reports into intel/
Report: rpt-07.txt
Date: 2026-09-14
Source: Harbour CERT
New analysis of Group Alder: the loader now calls home on port 9443. The address is unchanged. Earlier reports of port 8443 are out of date.
Claims:
- alder-c2-port = 9443
- alder-c2-address = 198.51.100.232. Save the search and the checks
Save intel.py. Path("intel").glob("rpt-*.txt") lists the report files. re.findall extracts the date and source lines and the claims with patterns. TfidfVectorizer(stop_words="english") turns each report into word weights and leaves out common English words (lesson 9 of "How AI works"). cosine_similarity measures how close two such vectors are, from 0 (nothing in common) to 1 (the same). search ranks the reports by closeness to the question. date.fromisoformat reads a date written as 2026-11-01, and subtracting two dates gives a time span with .days. re.M lets ^ match at the start of every line. setdefault(key, []) returns the list under a key, and makes an empty one first if there is none. [::-1] reverses a list, so the best match comes first.
conflicts collects every claim key and keeps the keys with more than one value. warnings lists the problems of one report, and it names the report that a conflict is with and whether that report is newer. With a question as text, it lists only the conflicts about the group that the question names. check_line checks one claim of an answer: it needs a source in square brackets, the source must exist, and one claim of that source must be in the text. "In the text" means that the line names the group of the claim key (alder in alder-c2-port) and holds its value as a whole word or number, so 9443 does not match 29443. The pattern does this with a look-behind and a look-ahead, as in lesson 3: (?<![\w.]) means "not directly after a letter, digit or dot", and (?!\w|\.\d) means "not directly before a letter, digit, or dot and digit". \b and rf are as in lesson 3.
intel.py
"""intel.py: search a small intel base, show sources, and check an answer against the base."""
import json
import re
import sys
from datetime import date
from pathlib import Path
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity
from gen import AS_OF
STALE_DAYS = 180
def load(folder="intel"):
"""Read every report. A report is a dict with its name, date, source, text and claims."""
base = {}
for path in sorted(Path(folder).glob("rpt-*.txt")):
text = path.read_text()
meta = dict(re.findall(r"^(Date|Source): (.+)$", text, re.M))
claims = dict(re.findall(r"^- (\S+) = (.+)$", text, re.M))
base[path.name] = {"date": meta["Date"], "source": meta["Source"], "text": text, "claims": claims}
return base
def search(base, question, k=3):
"""The k reports that are closest to the question, with their scores. Reports with score 0 are left out."""
names = list(base)
vec = TfidfVectorizer(stop_words="english")
matrix = vec.fit_transform([base[n]["text"] for n in names])
sims = cosine_similarity(vec.transform([question]), matrix)[0]
return [(names[i], round(float(sims[i]), 2)) for i in sims.argsort()[::-1][:k] if sims[i] > 0]
def conflicts(base):
"""Claim keys that two reports state with different values: {key: [(date, report, value), ...]}."""
seen = {}
for name, r in base.items():
for key, value in r["claims"].items():
seen.setdefault(key, []).append((r["date"], name, value))
return {k: sorted(v) for k, v in seen.items() if len({x[2] for x in v}) > 1}
def warnings(base, name, text=""):
"""Reasons to be careful with a report: stale, in conflict with another, or from an unverified source.
With a question or a claim as `text`, only the conflicts about a group that the text names are listed."""
r, out = base[name], []
if (date.fromisoformat(AS_OF) - date.fromisoformat(r["date"])).days > STALE_DAYS:
out.append("stale")
for key, entries in conflicts(base).items():
if key not in r["claims"] or (text and key.split("-")[0] not in text.lower()):
continue
for day, other, value in entries:
if value != r["claims"][key]:
out.append(f"conflict with {other} ({'newer' if day > r['date'] else 'older'})")
if "unverified" in r["source"].lower():
out.append("unverified")
return out
def check_line(base, line):
"""Check one claim of an answer. Returns "ok" or the reason that it fails."""
cited = re.findall(r"\[(rpt-\d+\.txt)\]", line)
if not cited:
return "no source"
if any(c not in base for c in cited):
return "unknown source"
low = line.lower()
for c in cited:
for key, value in base[c]["claims"].items():
group = re.escape(key.split("-")[0])
if re.search(rf"\b{group}\b", low) and re.search(rf"(?<![\w.]){re.escape(value.lower())}(?!\w|\.\d)", low):
return "ok"
return "claim not in source"
if __name__ == "__main__":
base = load()
question = " ".join(sys.argv[1:]) or "Which port does Group Alder use for command and control?"
print("question:", question)
for name, score in search(base, question):
r = base[name]
print(f" {name} score {score} {r['date']} {r['source']} {warnings(base, name, question) or ''}")
print("conflicts:", {k: [x[1] for x in v] for k, v in conflicts(base).items()})python3 intel.pyquestion: Which port does Group Alder use for command and control?
rpt-07.txt score 0.34 2026-09-14 Harbour CERT ['conflict with rpt-02.txt (older)']
rpt-02.txt score 0.25 2026-03-10 Harbour CERT ['stale', 'conflict with rpt-07.txt (newer)']
rpt-06.txt score 0.21 2026-07-07 Vendor Northwind
conflicts: {'alder-c2-port': ['rpt-02.txt', 'rpt-07.txt'], 'birch-target': ['rpt-03.txt', 'rpt-08.txt'], 'cedar-lure': ['rpt-06.txt', 'rpt-09.txt']}The two best matches are both about Group Alder's port, and they disagree: report 7 says 9443 and report 2 says 8443. The warnings tell you what to do. Report 2 is stale and in conflict with the newer report 7, so report 7 wins here. The third match, report 6, is about another group. It matched on shared words, its score is low, and it has no warning, because the question names no conflict of its group. A search always returns something.
3. Ask about another group
python3 intel.py "What does Group Birch target?"question: What does Group Birch target?
rpt-08.txt score 0.26 2026-09-30 Partner Blue Quay ['conflict with rpt-03.txt (older)']
rpt-03.txt score 0.24 2026-04-02 Vendor Northwind ['stale', 'conflict with rpt-08.txt (newer)']
rpt-04.txt score 0.2 2026-05-20 Partner Blue Quay
conflicts: {'alder-c2-port': ['rpt-02.txt', 'rpt-07.txt'], 'birch-target': ['rpt-03.txt', 'rpt-08.txt'], 'cedar-lure': ['rpt-06.txt', 'rpt-09.txt']}Report 8 says "VPN portals" and report 3 says "remote desktop gateways". Report 8 is newer and says in its own text that the group "has moved". A conflict is not always an error: the world changed. The analyst needs both facts and their dates, so that the story reads: first remote desktop gateways, now VPN portals.
4. Beware of "newest wins"
The last line of the output lists three conflicts. For two of them, the newest report is a trusted source. For cedar-lure the newest report, rpt-09, is a forum post with no proof. A rule that says "take the newest" would pick it. The unverified warning stops that. Only a person can resolve such a conflict, and the answer should show both.
5. Check an answer
claims-06.json holds ten claims that the course wrote, with the faults that a model makes. No model wrote them. They are fixed text, so every reader gets the same result. Save it.
claims-06.json
[
"Group Alder calls home on port 9443. [rpt-07.txt]",
"Group Alder calls home on port 8443. [rpt-02.txt]",
"Group Alder uses a loader that calls home on port 8443.",
"Group Birch targets VPN portals. [rpt-12.txt]",
"Group Cedar sends a fake tax notice email. [rpt-09.txt]",
"Group Alder calls home on port 443. [rpt-02.txt]",
"Group Birch targets VPN portals. [rpt-08.txt]",
"Group Alder installs a task named SyncHelper. [rpt-05.txt] [rpt-99.txt]",
"Group Birch calls home on port 9443. [rpt-07.txt]",
"Group Alder was founded in 1999 and calls home on port 29443. [rpt-07.txt]"
]python3 -c "
import json
from intel import *
base = load()
for line in json.load(open('claims-06.json')):
cited = re.findall(r'\[(rpt-\d+\.txt)\]', line)
print(check_line(base, line).ljust(22), [warnings(base, c, line) for c in cited if c in base])
"ok [['conflict with rpt-02.txt (older)']]
ok [['stale', 'conflict with rpt-07.txt (newer)']]
no source []
unknown source []
ok [['conflict with rpt-06.txt (older)', 'unverified']]
claim not in source [['stale', 'conflict with rpt-07.txt (newer)']]
ok [['conflict with rpt-03.txt (older)']]
unknown source [[]]
claim not in source [[]]
claim not in source [['conflict with rpt-02.txt (older)']]Six claims fail. The third has no source. The fourth cites rpt-12.txt, which does not exist. The sixth cites a real report but says port 443, which the report does not hold. The eighth cites one real and one invented file. The ninth gives a real port of the wrong group, and the tenth holds a port that only contains the real one (29443), next to an invented founding year, which the check cannot see. Four claims pass, and each of them carries a conflict warning. The second also cites a stale report, and the fifth an unverified post. A pass is not trust: the check proves that the source says it, not that the source is right.
Your turn
Use intel.py and the reports. Write a script that prints, for the whole base, the reports with a stale warning, the keys in conflict, and the claims of claims-06.json that pass check_line. Then answer from your own output.
Last, write the answer to "Which port does Group Alder use?" in two lines, each with its source and its warnings, as an analyst should read it.
Check yourself
Why does code check the source and not the model?
A model that invents a claim will also invent its source, with the same confidence. The claims of this lesson show the shapes: a missing source, a file that does not exist, a wrong value. A check by code is exact: the file is in the folder, or it is not.
The check passes a claim. Why may you still not trust it?
The check shows that the cited report holds the value. The report can be stale, in conflict with a newer one, or from a poor source. The check also looks for one claim only: an invented fact beside a correct claim passes. The warnings carry the information about the report, and a person decides.
Search returned report 6 for a question about Group Alder. What does that teach?
A ranking always returns the best of what it has, even when nothing is good. Show the scores, and drop a result below a limit that you choose. A low score is a sign that the base has no answer, and then "I do not know" is the right answer.
Why show both reports when two disagree?
The analyst needs the history, and the newest report may be wrong. Hiding a conflict hides a fact. A good answer shows each value with its date and source.
Field notes
- A report is untrusted text. A report from outside can hold words that read like an instruction to a model. Keep reports in a clearly marked block and do not let the helper act on what it reads (lesson 9). The course "Securing LLM applications" shows indirect prompt injection.
- Respect the sharing labels. Many partners mark a report with the Traffic Light Protocol (TLP), which says who may see it. A base that mixes labels needs access rules, and an answer must not leak a restricted report to a wider group.
- An indicator ages fast. An address that belonged to an attacker last year can belong to an honest customer today. Give every indicator a date and an expiry, and stop blocking on a stale one.
- Keep the claims structured. The
key = valuelines of the reports made the conflict check short. Text that nobody structured can only be searched. - Measure the base like a model: take 20 questions with known answers, and count how often the right report is in the top 3.