Lesson 08 · 50 minutes
Test which of your signals still work when attackers use AI
- Say for each family of AI-assisted attack what changes for the defender and which signal still works
- Show that a signature misses reworded variants and that a behaviour rule catches them
- Measure a reconnaissance footprint, a decoy hit and a spread-out flood in a web log
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
Your lead forwards a vendor note: "Attackers use AI to write endless variants of their programs, to scan faster and to flood sites. Signature rules are dead." (Lesson 7 covered mail and payments.) She asks: "For each claim, what changes for us and which of our checks still works? Show it on our own data." You get harmless samples, a day of the web log of www.harbourline.example, and public facts about one person. Nothing here runs an attack.
Recall
Lesson 7: why did an exact-duplicate test miss the burst of 26 mails?
Every text differed, so no two were equal. A test for one exact string misses a reworded copy.
Lesson 4: why is an unusual session not always an attack?
A backup job is unusual too. Unusual is a lead, and context decides.
The idea
A model rewords a text a hundred times in seconds, guesses the pages of a site, and drives many clients at once. The defender's question stays the same: which signal must the attacker still leave behind? Four families are taught in steps, and the fifth is in the Field notes.
| Family | What AI changes | Still works | Step |
|---|---|---|---|
| Obfuscation (hiding a text by encoding or rewording) and payloads (the part of an attack that does the harm) | Each copy is reworded. The signature (a known string or hash that a rule looks for) misses it | What the process does | 1, 2 |
| Malware variants | A new member of the family for each target. Hash lists miss it | Behaviour and family similarity | 1, 2 |
| Reconnaissance | Guesses that fit your site, slower, so the rate and the "not found" count miss it | Footprint: many paths, few repeats. A decoy | 3 to 5 |
| DDoS (distributed denial of service: many clients, so that the site cannot answer) | Many slow clients, so a limit per client misses it | Total load against normal | 3 to 5 |
| Automated data correlation | Many public sources joined about one target | Fewer public facts, and a process that ignores them | Field notes |
Three more are only named. Attack vector discovery finds the way in faster after an advisory (a published notice of a fault and its fix): count your days to patch. Adversarial inputs are tuned until a detector says "fine" (see the Field notes). Deepfakes and social engineering are lesson 7.
- Attacker → Model: same goal, new words each time
- Model → Host: four variants arrive
- Host → Signature rule: the text is compared with one string
- Signature rule → Alert: only 1 of 4 variants raises it
- Host → Behaviour rule: reads and connections are compared
- Behaviour rule → Alert: all 4 variants raise it
Worked example
1. Save the samples and the two rules
samples.json holds six samples. Each has an id, a label bad (for measuring only), a text and events (a list of [process, action, target]). The four hostile texts differ: the first holds the known string, the second uses other words, the third splits the string, and the fourth hides it in base64 (bytes written as letters). All four read a protected file and call the same outside address. The two normal samples are a backup to an inside server and an update from a vendor.
samples.json
[
{"id": "v1", "bad": true, "text": "copy /srv/finance/payroll-fake.txt then send it to 198.51.100.23",
"events": [[1, "read", "/srv/finance/payroll-fake.txt"], [1, "connect", "198.51.100.23:8443"]]},
{"id": "v2", "bad": true, "text": "take /srv/finance/payroll-fake.txt and upload the contents to host 198.51.100.23",
"events": [[1, "read", "/srv/finance/payroll-fake.txt"], [1, "connect", "198.51.100.23:8443"]]},
{"id": "v3", "bad": true, "text": "s = 'se' + 'nd it to 198.51' + '.100.23'; run(s, '/srv/finance/payroll-fake.txt')",
"events": [[1, "read", "/srv/finance/payroll-fake.txt"], [1, "connect", "198.51.100.23:8443"]]},
{"id": "v4", "bad": true, "text": "decode('c2VuZCBpdCB0byAxOTguNTEuMTAwLjIz') and run it on /srv/finance/payroll-fake.txt",
"events": [[1, "read", "/srv/finance/payroll-fake.txt"], [1, "connect", "198.51.100.23:8443"]]},
{"id": "n1", "bad": false, "text": "copy /srv/finance/payroll-fake.txt to the backup server 10.20.0.9",
"events": [[1, "read", "/srv/finance/payroll-fake.txt"], [1, "connect", "10.20.0.9:22"]]},
{"id": "n2", "bad": false, "text": "fetch the monthly updates from 192.0.2.80",
"events": [[1, "connect", "192.0.2.80:443"], [1, "write", "/tmp/updates-fake.tar"]]}
]Save detect.py. by_signature looks for one known string in the text. by_behaviour asks, for each process, whether it read a file under /srv/finance/ and also connected to an address outside 10.20.0.0/16. ip_address reads one address, ip_network makes a network from text, and in tests whether the address is inside it. any(...) is true if one item is true. {e[0] for e in ...} builds a set, so each process number is there once. sum(map(rule, bad)) applies the rule to each hostile sample and adds the answers (True is 1).
detect.py
"""detect.py: a signature rule and a behaviour rule, run on a file of samples."""
import ipaddress
import json
import sys
SIGNATURE = "send it to 198.51.100.23" # a string seen in the first sample
PROTECTED = "/srv/finance/"
INSIDE = ipaddress.ip_network("10.20.0.0/16") # the company network
def by_signature(sample):
return SIGNATURE in sample["text"]
def by_behaviour(sample):
"""True if one process read a protected file and connected to an outside address."""
for pid in {e[0] for e in sample["events"]}:
mine = [(action, target) for p, action, target in sample["events"] if p == pid]
read = any(action == "read" and target.startswith(PROTECTED) for action, target in mine)
out = any(action == "connect" and ipaddress.ip_address(target.split(":")[0]) not in INSIDE for action, target in mine)
if read and out:
return True
return False
if __name__ == "__main__":
samples = json.load(open(sys.argv[1] if len(sys.argv) > 1 else "samples.json"))
print(f"{'sample':8}{'hostile':>8}{'signature':>11}{'behaviour':>11}")
for s in samples:
print(f"{s['id']:8}{'yes' if s['bad'] else 'no':>8}{'HIT' if by_signature(s) else '-':>11}{'HIT' if by_behaviour(s) else '-':>11}")
bad = [s for s in samples if s["bad"]]
for name, rule in (("signature", by_signature), ("behaviour", by_behaviour)):
print(f"{name}: caught {sum(map(rule, bad))} of {len(bad)} hostile, false alarms {sum(rule(s) for s in samples if not s['bad'])}")python3 detect.py samples.jsonsample hostile signature behaviour
v1 yes HIT HIT
v2 yes - HIT
v3 yes - HIT
v4 yes - HIT
n1 no - -
n2 no - -
signature: caught 1 of 4 hostile, false alarms 0
behaviour: caught 4 of 4 hostile, false alarms 02. Read the result
The signature rule catches only the sample that it was written from. The behaviour rule reads what the process did: the data must be read, and it must leave. The four lists of events are identical because the goal is the same, and a variant that changes what the process does, such as w2 in "Your turn", can still pass. The backup n1 passes, because it connects to an inside address. Keep the signature too: it is cheap and exact.
3. Save the web log
weblog.py writes access.log, one day of requests: time, client, method, path and status (200 is "found", 404 is "not found"). It holds 30 ordinary clients and four patterns: a fast scanner that guesses common names (203.0.113.90), a slow scanner that guesses names that fit the site (198.51.100.77), one client that sends 600 requests to /search in a minute (203.0.113.140), and 45 clients that each send two requests a minute (198.51.100.100 to .144). The fast scanner also asks once for /old-admin/, a honeypot: a decoy that no link points to, so any touch is a lead.
The finished file: weblog.py
weblog.py
"""weblog.py: write access.log, one day of web requests to www.harbourline.example. Every client is invented.
python3 weblog.py write access.log and print how many lines it has
"""
import random
PAGES = ["/", "/login", "/tracking", "/tracking/status", "/quote", "/contact", "/account", "/account/orders",
"/static/app.js", "/static/site.css"]
AREAS = ["tracking", "quote", "account", "contact", "static"]
WORDS = ["export", "api", "pdf", "csv", "debug", "backup", "admin", "config", "test", "old", "new", "v1", "v2", "list",
"report", "invoice", "users", "upload", "download", "status", "health", "metrics", "search", "print", "mobile",
"partner", "labels", "rates"]
r = random.Random(8801)
rows = [] # (second of the day, client, path, status)
def at(h, m, s=0):
return h * 3600 + m * 60 + s
for n in range(30, 60): # 30 staff and customers
for _ in range(r.randint(25, 45)):
path, status = r.choice(PAGES), 200
if r.random() < 0.04:
path, status = path + "x", 404 # a typing mistake
rows.append((r.randint(at(8, 0), at(17, 59)), f"192.0.2.{n}", path, status))
for _ in range(420): # scanner A: fast, guesses common names
path = "/" + r.choice(WORDS) + r.choice(["", "/", ".php", ".bak", ".zip", ".old", ".txt"]) + r.choice(["", "/" + r.choice(WORDS)])
rows.append((r.randint(at(10, 0), at(10, 2, 59)), "203.0.113.90", path, 200 if r.random() < 0.03 else 404))
rows.append((at(10, 1, 30), "203.0.113.90", "/old-admin/", 200)) # the decoy page that no link points to
for area in AREAS: # scanner B: slow, guesses names that fit this site
for word in WORDS:
rows.append((r.randint(at(8, 30), at(17, 30)), "198.51.100.77", f"/{area}/{word}", 200 if r.random() < 0.65 else 404))
for _ in range(600): # flood D: one client, far too fast
rows.append((at(10, 10) + r.randint(0, 59), "203.0.113.140", "/search?q=" + str(r.randint(1000, 9999)), 200))
for n in range(100, 145): # flood E: 45 clients, each one slow, spread out
for minute in range(30, 45):
for _ in range(2):
rows.append((at(10, minute, r.randint(0, 59)), f"198.51.100.{n}", "/search?q=" + str(r.randint(1000, 9999)), 200))
rows.sort()
with open("access.log", "w") as f:
for s, ip, path, status in rows:
f.write(f"{s // 3600:02d}:{s % 3600 // 60:02d}:{s % 60:02d} {ip} GET {path} {status}\n")
print("access.log:", len(rows), "requests")python3 weblog.py
head -3 access.logaccess.log: 3548 requests
08:01:01 192.0.2.54 GET /tracking/status 200
08:01:09 192.0.2.31 GET /quote 200
08:01:51 192.0.2.51 GET /contact 2004. Measure what each client did
Save footprint.py. read cuts the query (the part of a path after ?), so that /search?q=1 and /search?q=2 are one path. by_client measures for each client the requests, the different paths, the repeat share (1 minus paths divided by requests), the share of 404 answers and the busiest minute. defaultdict(list) is a dict that starts each new key with an empty list. Counter counts items (lesson 7), and median is the middle value. RULES holds four tests, each a small function written with lambda. busy_minutes finds the minutes in which all clients together sent more than ten times the median minute (m, *_ takes the first item of a row and ignores the rest). sorted(..., key=lambda kv: -kv[1]["requests"]) puts the client with the most requests first.
footprint.py
"""footprint.py: measure each client of access.log and test four rules."""
from collections import Counter, defaultdict
from statistics import median
DECOY = "/old-admin/"
RATE = 100 # rule 1: requests of one client in one minute
SHARE_404 = 0.5 # rule 2: share of "not found" answers
MIN_PATHS, MAX_REPEAT = 50, 0.3 # rule 3: many different paths, few repeats
def read(name="access.log"):
"""Returns (minute of the day, client, path, status) for each line."""
rows = []
for line in open(name):
t, ip, _, path, status = line.split()
rows.append((int(t[:2]) * 60 + int(t[3:5]), ip, path.split("?")[0], int(status))) # the path without its query
return rows
def by_client(rows):
"""The numbers of each client."""
seen = defaultdict(list)
for minute, ip, path, status in rows:
seen[ip].append((minute, path, status))
out = {}
for ip, reqs in seen.items():
paths = {p for _, p, _ in reqs}
out[ip] = {"requests": len(reqs), "paths": len(paths), "repeat": 1 - len(paths) / len(reqs),
"share404": sum(s == 404 for _, _, s in reqs) / len(reqs),
"peak": max(Counter(m for m, _, _ in reqs).values()),
"decoy": any(p == DECOY for _, p, _ in reqs)}
return out
def busy_minutes(rows, factor=10):
"""Minutes with more than `factor` times the median requests of a working minute."""
minutes = Counter(m for m, *_ in rows)
return sorted(m for m, n in minutes.items() if n > factor * median(minutes[m] for m in range(480, 1080)))
RULES = {"rate": lambda c: c["peak"] > RATE, "404 share": lambda c: c["share404"] > SHARE_404,
"footprint": lambda c: c["paths"] >= MIN_PATHS and c["repeat"] < MAX_REPEAT, "decoy": lambda c: c["decoy"]}
if __name__ == "__main__":
rows = read()
clients = by_client(rows)
print("requests:", len(rows), " clients:", len(clients))
print(f"{'client':16}{'requests':>9}{'paths':>7}{'repeat':>8}{'404':>6}{'peak/min':>10}")
for ip, c in sorted(clients.items(), key=lambda kv: -kv[1]["requests"])[:4]:
print(f"{ip:16}{c['requests']:>9}{c['paths']:>7}{c['repeat']:>8.2f}{c['share404']:>6.2f}{c['peak']:>10}")
print("clients flagged by each rule:")
for name, rule in RULES.items():
print(f" {name:10}", sorted(ip for ip, c in clients.items() if rule(c)))
fast = {ip for ip, c in clients.items() if RULES["rate"](c)}
print("busy minutes:", len(busy_minutes(rows)), " still busy without the clients of the rate rule:",
len(busy_minutes([r for r in rows if r[1] not in fast])))python3 footprint.pyrequests: 3548 clients: 78
client requests paths repeat 404 peak/min
203.0.113.140 600 1 1.00 0.00 600
203.0.113.90 421 348 0.17 0.97 142
198.51.100.77 140 140 0.00 0.32 3
192.0.2.41 44 11 0.75 0.02 2
clients flagged by each rule:
rate ['203.0.113.140', '203.0.113.90']
404 share ['203.0.113.90']
footprint ['198.51.100.77', '203.0.113.90']
decoy ['203.0.113.90']
busy minutes: 19 still busy without the clients of the rate rule: 155. Read what each family leaves behind
- The fast scanner (
203.0.113.90) trips every rule. - The slow scanner (
198.51.100.77) sends at most 3 requests a minute for names that fit the site, so 68 percent of its answers are 200. Only the footprint rule sees it: 140 paths, no repeats, where staff repeat between 0.58 and 0.75. It never touched the decoy (honeypot evasion): a decoy catches careless tools, not careful ones, so test it like a detector. - The single flood (
203.0.113.140) is the case of the rate rule. - The spread-out flood has 45 clients at 2 requests a minute, far under the limit, so no client is flagged. The total shows it: 15 busy minutes remain.
No rule is enough alone. The footprint and decoy rules can flag a search crawler, so a person confirms before a block.
Your turn
Save more.json, two new hostile samples (w2 works in two stages: process 1 writes a cache, and process 2 sends it). Run detect.py on it. Then set MIN_PATHS in footprint.py to 150, run it again, and put it back to 50.
more.json
[
{"id": "w1", "bad": true, "text": "forward /srv/finance/payroll-fake.txt towards 203.0.113.200 over port 443",
"events": [[1, "read", "/srv/finance/payroll-fake.txt"], [1, "connect", "203.0.113.200:443"]]},
{"id": "w2", "bad": true, "text": "stage 1 copies /srv/finance/payroll-fake.txt to a cache, stage 2 sends the cache to 203.0.113.200",
"events": [[1, "read", "/srv/finance/payroll-fake.txt"], [1, "write", "/tmp/cache-fake.bin"],
[2, "read", "/tmp/cache-fake.bin"], [2, "connect", "203.0.113.200:443"]]}
]Last, write two sentences on how by_behaviour could follow a file from one process to the next. The page does not check this.
Check yourself
Why does a behaviour rule survive a reworded variant when a signature does not?
A signature reads words that a model changes at no cost. A behaviour rule reads what the process must do, and that stays.
A GAN (see the Field notes) trains a maker against a judge. When does that make your detector weak?
Only when the attacker can test fakes against a detector like yours. So limit what the detector shows about its decisions, retrain on new fakes, and keep signals that ignore the content, such as who sent it.
Four public sources (see the Field notes) name the CFO. Which control of lesson 7 stops a mail that quotes her talk and her travel dates, and why?
The call-back rule. The facts are public, so quoting them proves nothing. The rule calls the real CFO on a directory number.
Field notes
Public facts add up. Automated data correlation joins many public sources about one target. A model does it for a hundred pages in seconds. Four invented public sources name the CFO of Harbourline:
| Source | Fact about Priya Nair |
|---|---|
| Staff page | Role: CFO |
| Conference list | Talk: "our new freight bank portal" |
| Old leak | Personal mail: p.nair@mail.example |
| Press note | Travel: in Rotterdam, 12 to 14 March |
Each fact is harmless alone. Joined on the name, they give a role, a talk, a private address and travel dates. A mail about the freight portal "while you are in Rotterdam" would be believable, and every fact is public. You cannot stop the join. You can publish fewer facts, and use a process that ignores them: the call-back rule of lesson 7.
GAN. A generative adversarial network (GAN) trains two models against each other: a maker makes samples, a judge tries to tell them from real ones, and the maker improves until the judge fails. If an attacker can query your detector, the attacker can use it as that judge.
- In MITRE ATT&CK, reconnaissance is the tactic TA0043, "Obfuscated Files or Information" is technique T1027 and "Network Denial of Service" is T1498. Take the current text from MITRE. MITRE ATLAS covers attacks on AI systems.
- Adversarial inputs: change your own samples as an attacker would, and count what still gets caught.
- Run scanners and floods only against your own lab.