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 12 · 50 minutes

Check the output of AI tools for threats, tests and payments

After this lesson you can
  • Check a threat list against your own list of data flows
  • Check a penetration-test report against the scope
  • Check a fraud score against a rule that ignores the score
Lab files of this lesson (53)

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

A manager asks whether AI can also list the shop's threats, test the shop, and find fraud in payments. Your lead says yes to all three, with one condition: each output is a lead, and code checks it against facts that you hold. The tools here are stubs that the course wrote, with the usual faults planted in them.

Recall

Lesson 11: what do you count when you check an AI review, and which three numbers does verify.py print?

The true claims, the invented ones and the faults that the review missed. A claim is checked against the code, and a fault that the review never mentions is found by a scanner.

Lesson 7: what does the call-back rule do for a payment?

A person calls the payee on a number that the company already holds, before the money or the bank details change. A mail or a score cannot replace that call.

The idea

Three uses of AI give a list or a score. In each, a person must check what the tool says, and a short program can do the first half of the check.

UseThe tool producesA person must check
AI-assisted threat modellingA model lists threats for a designEach threat against the real data flows, and what the list missed
Automated penetration testingA tool probes a system with no person at the keyboard and lists the steps that workedThat the system is yours and the test is allowed, that each finding can be repeated, and its risk
Fraud detectionA score for each payment, by how unusual it is (the idea of lesson 4)Each flagged payment, because unusual is not fraud, and each quiet one, because usual is not safe

The method is the same each time: the output is in a file with a fixed shape, your facts are in another file, and code compares them.

An AI list is checked against your facts
AI toolYour labPersonModel outputCheckerYour factsAnalyst123AI toolYour labPersonModel outputCheckerYour factsAnalyst123
  1. Model output → Checker: a list of items, each with a name
  2. Checker → Your facts: is the name in your list?
  3. Checker → Analyst: items that fail, and facts with no item

Worked example

1. Check a threat list against the data flows

flows.txt is the lab's own list of data flows: the facts. threats-stub.json is a stub in the shape of a model's threat list. Each threat names a flow.

flows.txt

customer browser -> shop app
shop app -> orders database
shop app -> label printer service

threats-stub.json

[
  {"id": "T1", "flow": "customer browser -> shop app", "threat": "An order id with a quote changes the SQL text."},
  {"id": "T2", "flow": "shop app -> label printer service", "threat": "The key in the request header is read from the code."},
  {"id": "T3", "flow": "shop app -> payment provider", "threat": "A card number is stolen on its way to the provider."}
]

Save threats.py. It checks that the flow of each threat is in the list, and it prints each flow that has no threat. It compares exact text, so the prompt to a real model must say "name each flow exactly as in flows.txt". Your turn relaxes this.

threats.py

"""threats.py: check each threat of an AI list against the data flows of the lab."""
import json
import sys

flows = [line.strip() for line in open(sys.argv[1]) if line.strip()]
threats = json.load(open(sys.argv[2]))
for t in threats:
    print(t["id"], t["flow"] + ":", "the flow is in the list" if t["flow"] in flows else "NO SUCH FLOW in the list")
for flow in flows:
    if not any(t["flow"] == flow for t in threats):
        print("a flow with no threat:", flow)
python3 threats.py flows.txt threats-stub.json
T1 customer browser -> shop app: the flow is in the list
T2 shop app -> label printer service: the flow is in the list
T3 shop app -> payment provider: NO SUCH FLOW in the list
a flow with no threat: shop app -> orders database

T3 does not apply, because the shop has no payment provider. The tool also left out the flow to the database. Code finds both, but it cannot find a threat that the model never thought of, so a person still reads the design.

2. Check a penetration-test report against the scope

A tool for automated penetration testing tests a system without a person at the keyboard. It may follow a link to a host that you never meant it to touch. The scope is the list of systems that you have written permission to test. scope.txt holds three lab hosts. pentest-stub.json is a stub report of four findings, each with a host, a text and the steps to repeat it: F2 has no steps, and F3 is on a partner's host. pentest.py asks two questions for each finding, in this order: is the host in the scope, and are there steps to repeat it? Save the three files from this block.

The finished files: scope.txt, pentest-stub.json and pentest.py

scope.txt

shop.lab.example
db.lab.example
label.lab.example

pentest-stub.json

[
  {"id": "F1", "host": "shop.lab.example", "finding": "The admin page accepts the password admin",
   "repeat": "open /admin and sign in as admin with the password admin"},
  {"id": "F2", "host": "db.lab.example", "finding": "The database port answers from the office network", "repeat": ""},
  {"id": "F3", "host": "portal.partner.example", "finding": "The login page shows the version number",
   "repeat": "open /login and read the footer"},
  {"id": "F4", "host": "label.lab.example", "finding": "The label service accepts a request with no key",
   "repeat": "send a request to /print with no Authorization header"}
]

pentest.py

"""pentest.py: check each finding of an automated test against the scope and for steps to repeat it."""
import json
import sys

scope = [line.strip() for line in open(sys.argv[1]) if line.strip()]
report = json.load(open(sys.argv[2]))
usable = 0
for f in report:
    if f["host"] not in scope:
        verdict = "OUT OF SCOPE: do not report it as a finding; tell the owner of the test"
    elif not f["repeat"]:
        verdict = "no steps to repeat it: a lead only"
    else:
        verdict = "in scope: repeat it by hand"
        usable += 1
    print(f["id"], f["host"] + ":", verdict)
print("findings to repeat by hand:", usable, "of", len(report))
python3 pentest.py scope.txt pentest-stub.json
F1 shop.lab.example: in scope: repeat it by hand
F2 db.lab.example: no steps to repeat it: a lead only
F3 portal.partner.example: OUT OF SCOPE: do not report it as a finding; tell the owner of the test
F4 label.lab.example: in scope: repeat it by hand
findings to repeat by hand: 2 of 4

Two findings go on to a person, who repeats them on the lab host and rates the risk. F3 is the serious one: the tool touched a partner's system. Never add a host to scope.txt to make a finding pass, because the scope is the permission and not a setting.

3. Check a fraud score against a rule that ignores it

A fraud tool scores each payment by how unusual it is, as the detector of lesson 4 does. payments.json holds the list of known payees with their bank accounts, and eight payments. Each payment has a score from the tool; the course wrote these numbers. Save it from this block.

The finished file: payments.json

payments.json

{"payees": {"Rotterdam Parts": "NL-4410", "Dock Services": "NL-5521", "Fuel Card Co": "NL-7003",
            "Harbourline payroll": "NL-1000", "Office Supplies": "NL-3302"},
 "payments": [
  {"id": "P01", "payee": "Rotterdam Parts", "account": "NL-4410", "amount": 420, "score": 0.04},
  {"id": "P02", "payee": "Dock Services", "account": "NL-5521", "amount": 515, "score": 0.05},
  {"id": "P03", "payee": "Fuel Card Co", "account": "NL-7003", "amount": 610, "score": 0.06},
  {"id": "P04", "payee": "Harbourline payroll", "account": "NL-1000", "amount": 7600, "score": 0.91},
  {"id": "P05", "payee": "Rotterdam Parts", "account": "NL-9917", "amount": 380, "score": 0.12},
  {"id": "P06", "payee": "Nordic Freight Ltd", "account": "NL-8842", "amount": 450, "score": 0.18},
  {"id": "P07", "payee": "Office Supplies", "account": "NL-3302", "amount": 300, "score": 0.03},
  {"id": "P08", "payee": "Baltic Marine Ltd", "account": "NL-6120", "amount": 9800, "score": 0.88}
 ]}

Save fraud.py. A rule holds a payment if the payee is new, or if a known payee has a different account: the usual sign of a redirected invoice. The rule never looks at the score. The program prints every payment that the rule holds or the tool flags (SCORE_LIMIT is where the tool flags), then three counts. held - flagged is the set of ids that are in held and not in flagged.

fraud.py

"""fraud.py: check the scores of a fraud tool against the list of payees. Exit code 1 if a payment is held."""
import json
import sys

SCORE_LIMIT = 0.5                     # the tool flags a payment at this score or more


def hold_reason(payment, payees):
    """Why the payee rule holds a payment, or an empty text."""
    account = payees.get(payment["payee"])
    if account is None:
        return "NEW PAYEE"
    return "" if account == payment["account"] else "ACCOUNT CHANGED"


data = json.load(open(sys.argv[1]))
held, flagged = set(), set()
for p in data["payments"]:
    reason = hold_reason(p, data["payees"])
    if reason:
        held.add(p["id"])
    if p["score"] >= SCORE_LIMIT:
        flagged.add(p["id"])
    if reason or p["id"] in flagged:
        print(f"{p['id']}  {p['payee']:20}{p['amount']:>6}  score {p['score']:.2f}  {reason or 'payee and account are known'}")
print("held by the payee rule:", len(held))
print("flagged by the score:", len(flagged))
print("held by the rule, not flagged by the score:", len(held - flagged))
sys.exit(1 if held else 0)
python3 fraud.py payments.json; echo "exit code $?"
P04  Harbourline payroll   7600  score 0.91  payee and account are known
P05  Rotterdam Parts        380  score 0.12  ACCOUNT CHANGED
P06  Nordic Freight Ltd     450  score 0.18  NEW PAYEE
P08  Baltic Marine Ltd     9800  score 0.88  NEW PAYEE
held by the payee rule: 3
flagged by the score: 2
held by the rule, not flagged by the score: 2
exit code 1
Payments out of 8, by control
Flagged by the score2Held by the payee rule3Held by rule, not flagged2Flagged by the score2Held by the payee rule3Held by rule, not flagged2

The score flags the month-end payroll P04, which is unusual and fine: the payee and account are known. It gives P05 and P06 a low score, and both are the kind of payment that fraud uses. The rule holds them without any score. A person confirms each held payment with the call-back rule of lesson 7, and only then changes the list of payees.

Your turn

Work in copies, so that the files of the lesson stay as they are.

  1. A model's second threat list adds T4 on the flow Shop App -> Orders Database (capitals and two spaces) and T5 on shop app -> orders. T4 is a flow of yours in other writing. T5 names no flow of yours. Change a copy of threats.py so that capitals and extra spaces do not matter and a shortened name still fails (text.lower() and " ".join(text.split()) help). Add T4 and T5 to a copy of the stub, with any threat text, and run it.
  2. The tool's second report adds F5 on admin.shop.lab.example (repeat: open /admin and view the page source) and F6 on label.lab.example (repeat: send a request to /print/x and read the error page). The owner said by telephone that the admin host may be tested too. You have no paper. Add F5 and F6 to a copy of the stub, decide what to do with scope.txt, and run pentest.py.
  3. Two call-backs are done. Nordic Freight Ltd confirmed the account NL-8842. At Rotterdam Parts, nobody knows the account NL-9917. Decide which of the two changes the list of payees, change it in a copy of payments.json, and run fraud.py.

Last, write two sentences on which of the three uses you would allow first, and what a person checks. The page does not check this.

Check yourself

A tool for automated penetration testing reports a weak password on a host. What do you do before you write it up?

Check that the host is in the scope that you have permission to test. Then repeat the step by hand and rate the risk. A tool finds leads at speed, and the person answers for the result.

The fraud tool gives the payroll payment 0.91 and a payment to a new payee 0.18. What do the two scores show?

Unusual is not fraud, and usual is not safe. The score sees amount and pattern. A rule on the payee and account, and a call-back, cover what the score cannot see.

threats.py prints no "NO SUCH FLOW" and no "a flow with no threat". Is the threat list complete?

No. The check compares names of flows only. It cannot tell whether a threat is true, or whether the model missed a threat on a flow that has another threat. A person still reads the design.

Field notes

  • Keep a scope list for penetration testing, with the written permission: a tool that follows a link to another host must stop at the list. Log each request that it makes.
  • To use a real model for a threat list, ask for JSON in the shape of threats-stub.json, and run threats.py on what comes back. Treat a threat that fails the check as a model fault, not as a finding.
  • A real fraud model learns from past payments, so a pattern that is new to it gets a low score. Keep rules on facts that do not change, such as the account of a payee, beside it.
  • Check a translated alert in the same way: take the addresses and hashes out of both texts with a pattern, compare the two sets, and send the alert back to a person when they differ. One swapped digit in an address makes a partner block the wrong host. A passing check proves only that the indicators are the same, and a person who reads the language still checks the text.