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

Advanced / AI for security operations

AI for security operations cheat sheet

Set up the lab (lesson 0)

TaskCommand or code
Make the lab foldermkdir -p ~/krlab/ai-for-secops
Make and switch on the environmentpython3 -m venv .venv, source .venv/bin/activate
Install the pinned librariespip install -r requirements.txt
Show the size and the fingerprint of the datapython3 gen.py
Prove the lab workspython3 labcheck.py (last line lab ready: 9 of 9)
Skip the model if your computer cannot run itexport KR_NO_MODEL=1 (last line lab ready: 7 of 7)

Measure the work and the baseline (lesson 1)

TaskCommand or code
Load the fixed week of alertsfrom gen import alerts then alerts(5)
Print the workload and the baselinepython3 workload.py
Count by a fieldCounter(a["rule"] for a in week).most_common()
Read the first N of each day in a chosen orderreached(week, lambda a: (-a["asset"], a["id"]))
Change the capacity of a dayCAPACITY in workload.py

Triage with a model (lesson 2)

TaskCommand or code
Train on weeks 1 to 4from triage import train, scores then model = train()
Train on other weekstrain([3, 4])
Score a week (a ranking score, not a probability)scores(model, week)
Precision and recall at a cut-offprecision_score(y, pred), recall_score(y, pred)
Cost table of auto-closingpython3 threshold.py
State the threshold as a rule"Auto-closing may miss at most N incidents in 10"
Choose it on a week that you do not reportchoose(week4, score4)

Summarise a log and check it (lesson 3)

TaskCommand or code
Find the key facts by codefacts(case_log())
Rule-based summarysummarise(case_log())
Prompt for the modelprompt(case_log())
Check a summary (empty list is a pass)check(text, facts(log), log)
Test the checker with hand-written summariespython3 test_check.py
Ask the model (temperature 0 and a fixed seed repeat a run)chat([{"role": "user", "content": prompt(log)}], seed=1, temperature=0)
Ask the model once and checkpython3 ask_model.py

Find anomalies (lesson 4)

TaskCommand or code
Largest z-score of each sessionzscores(X)
Isolation forest scores and alertsscore, flag = isolation(X, contamination=0.02)
Compare with the same budgetin_top(z.argsort()[::-1], rows, 8)
Run both detectorspython3 anomaly.py

Classify messages (lesson 5)

TaskCommand or code
Messages in the old and in the new stylemessages(1, 600), messages(3, 200, "new")
Three numbers from the message (urgent words is the wording control)extra(message) gives urgent words, link, mismatch
Train with or without the three numberspredict = build(train, use_extra=True)
Precision and recall, roundedmeasure(predict, rows)
Run the comparisonpython3 phish.py

Use intelligence with sources (lesson 6)

TaskCommand or code
Write the reportspython3 gen.py intel
Search with sourcespython3 intel.py "Which port does Group Alder use?"
Keys that two reports state differentlyconflicts(base)
Stale, conflict or unverified reportwarnings(base, "rpt-02.txt", question)
Check one claim of an answer (group and whole value)check_line(base, line) gives ok or the reason

Recognise AI-enhanced attacks (lesson 7)

TaskCommand or code
Find a burst of near-copiespython3 bursts.py
Change how similar texts must bebursts(rows, similar=0.7)
Display name of an executive, foreign addressfake_executive(message)
Hold a payment that skips the approvalhold(request) returns the reasons
Run the payment rulepython3 approvals.py

See what changes when attackers use AI (lesson 8)

TaskCommand or code
Write the web log of the daypython3 weblog.py
Signature rule against behaviour rule on samplespython3 detect.py samples.json
Hit of the signature rule, hit of the behaviour ruleby_signature(sample), by_behaviour(sample)
Measure each client of the log and test four rulespython3 footprint.py
Repeat share of a client1 - paths / requests (low for a scanner, 0.58 to 0.75 for staff)
Minutes of a flood that no client's rate showsbusy_minutes(rows)

Automate safely (lesson 9)

TaskCommand or code
Enrich one alertpython3 enrich.py W5-0003
Dry run of a suggestion (default)python3 gate.py suggestion.json
Apply an action that needs no approvalpython3 gate.py suggestion.json --apply
Apply with a named approverpython3 gate.py suggestion.json --apply --approved-by sam
Exit codes of the gate0 done, 1 refused, 2 waiting for approval
Verdict for a suggestiongate.decide(suggestion) gives allow, approval or refuse
Prove the gate with a tablepython3 test_gate.py
Read the audit logcat audit.log

Gate a change with scanners, tests and a pipeline (lesson 10)

TaskCommand or code
Make the folders of the lessoncd ~/krlab/ai-for-secops, mkdir -p shop drafts
Rule check of a folder (exit code 1 on a security problem)python3 lint.py shop
Composition scan against advisories, and the SBOMpython3 sca.py shop/requirements.txt advisories.json, cat sbom.json
Run the tests of the shop codepython3 test_app.py
Test the model against a floorpython3 model_test.py
Run every check, exit code is the gatepython3 pipeline.py; echo $?
See why one step failedrun that step alone, for example python3 lint.py shop

Check an AI review and control the AI helpers (lesson 11)

TaskCommand or code
Check each AI finding against the faulty originalpython3 verify.py drafts/app-faulty.py ai-review-stub.json
Check the installed helpers against the allowlistpython3 helpers.py installed.json allowlist.json; echo $?

Check the output of AI tools (lesson 12)

TaskCommand or code
Check an AI threat list against the data flowspython3 threats.py flows.txt threats-stub.json
Check a penetration-test report against the scopepython3 pentest.py scope.txt pentest-stub.json
Check fraud scores against the payee rulepython3 fraud.py payments.json; echo $?

Run the copilot and the build (lessons 13 and 14)

TaskCommand or code
Review three proposals yourselfpython3 copilot.py ask 3
Run the fixed week with a simulated reviewerpython3 copilot.py week
Which alerts a person must readREVIEW_FROM (score) in copilot.py
Run every part and the table of partspython3 triage_copilot.py
A reviewer who accepts every proposal to closesimulated_reviewer(labels, sees_all=False)
Errors against the labelserrors(records, labels) gives missed and false alarms

Evaluate on a new week (lesson 15)

TaskCommand or code
The new week with a shifted patternalerts(6, shift=True)
Alerts closed and incidents missedcount verdict == "close" and label == 1
Rules that the training weeks never had{a["rule"] for w in (1, 2, 3, 4) for a in alerts(w)}
The day of mail for the burst rulemail_stream() then bursts(rows)
Evaluation of a copilotevaluation.md: tested, reported, misses, recommendation, open

Safety habits

HabitWhy
A model proposes, and a person or an approved rule decidesThe model has no accountability and can be wrong or misled.
Count the silent misses before you auto-closeAccuracy hides them. Report recall and the count of missed incidents.
Choose the threshold from a rule about risk, not 0.50.5 is a default of the library.
Choose the threshold on one week and report anotherA threshold chosen on the test week makes the report too good.
Measure on a new week, not on the training dataA pattern that shifts lowers recall, and no score warns you.
Find facts by code and check every summaryA fluent summary can lose or invent a fact.
Every claim carries a source, and code checks itRetrieval lowers invention and does not remove it. Read stale, conflict and unverified warnings.
Rely on controls that do not depend on judging the messageCall-back, out-of-band approval, dual control, domain and header checks.
Detect what the attacker must do, not the words that they chooseA signature misses a reworded variant. Behaviour, footprint and total load stay.
Treat an AI review as leads and a scanner or test as the gateA review can invent a fault and miss one. Verify each finding against the code.
Check what an AI tool lists against your own facts, by codeA threat list can name a flow that does not exist, and a scan can report a host that is not in the scope.
Allow-list every AI plug-in and assistant, and say what it reads and sendsEach one reads your data and can act in your name.
Allowlist, dry run, approval, audit lineThe gate keeps a wrong suggestion from becoming an action.
Test every control with a table that has hostile rowsA checker or a gate that nobody attacked has holes that you have not seen.
Log the score, the evidence and the decision of every alert"Why was it closed?" needs an answer.
Sample what was closed with no reviewIt is your live estimate of the silent miss rate.
Use invented data and your own lab onlyNever put real logs or real mail into a prompt or a lab.