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 06 · 45 minutes

Test the infrastructure around the model

After this lesson you can
  • Check which ports of the lab listen, and on which address
  • Find a missing login, a debug page, a key in a log and an unbounded request with scripts
  • Fix each finding on the lab target and run the same checks again
Lab files of this lesson (31)

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

So far you tested what the model says and does. Your lead reminds you that the assistant is also a web service: "A chat system gets broken through its login, its logs and its debug page more often than through its prompt." You test the layer around the model on the lab target with five small checks, you fix what you find, and you run the checks again.

Recall

Lesson 1: why must a request to a path that the scope does not name be refused, and not only warned about?

A warning can be ignored at 17:00 on a Friday. A refusal in code cannot. The owner decides what the scope says, and the program enforces it.

Lesson 2: the scan of `repo-sample` printed only the first four characters of each secret. Why?

A scanner that prints full secrets spreads them into saved output and reports. Four characters help you find the line, and the file name and line number lead you to the rest.

The idea

The model is one part of the system. Around it sit layers that were old before language models: a network port, a login, a web page for the developer, a log file, a limit on the size of a request. A weakness in one of them can be worse than any prompt trick, because it needs no cleverness. The OWASP GenAI Red Teaming Guide names infrastructure assessment as one of its four areas. OWASP Unbounded Consumption (LLM10 in the 2025 list) is the risk that a request can cost more than you meant to give.

Layers around the model, outside in
Networkwhich address a port listens onLoginwho may send a request at allPages and routesa debug page that shows too muchLogs and filesa key that was written downLimitsthe size and the rate of a requestNetworkwhich address a port listens onLoginwho may send a request at allPages and routesa debug page that shows too muchLogs and filesa key that was written downLimitsthe size and the rate of a request

Each layer has one question and one check:

CheckQuestionA finding is
ports.pyDoes a port listen on more than the loopback address?An address of 0.0.0.0, * or [::]
no-loginDoes the chat endpoint answer a request with no credentials?Status 200
debug-pageDoes /debug answer?Status 200 (and a key in the page)
key-in-logDoes the newest log line hold a secret?A match of the key pattern from lesson 2
unbounded-bodyIs a request of 100000 characters accepted?Status 200

A check passes only on the refusal that it expects: 401 or 403 for no-login, 403 or 404 for debug-page, 400 or 413 for unbounded-body. Any other status (a 500, or a 401 from a wrong token) is an error, never an "ok". Every check uses call from lesson 1, so the scope still guards you. The checks run against the stub. Do not send a 100000 character message to the live model: it would keep your computer busy for minutes.

Worked example

1. Check the listening addresses

Who can reach the ports
Your computerThe networkTarget (8410)YouModel server (11434)Other machine123Your computerThe networkTarget (8410)YouModel server(11434)Other machine123
  1. You → Target (8410): request on 127.0.0.1
  2. You → Model server (11434): lists models, no login
  3. Other machine → Model server (11434): reaches it only if bound to 0.0.0.0

ss -ltn (socket statistics: listening, TCP, numbers) lists the ports that your computer listens on, with the address of each. An address of 127.0.0.1 means "this computer only". 0.0.0.0, * and [::] mean "every network interface", so any machine on the network can try the port. ports.py reads that list and compares it with the ports of your scope. subprocess.run starts a program and collects its output, and rpartition(":") splits an address at its last colon. One port can listen on two addresses, so ports.py keeps a list for each port (setdefault(key, []) returns the list of a key and first creates an empty one when the key is new) and flags the port if any of them is open to everyone.

ports.py

"""ports.py: which ports of the scope answer, and on which address each one listens.

    python3 ports.py            read the real listeners with ss (Linux)
    python3 ports.py ss.txt     read saved output of 'ss -ltn'
"""
import subprocess
import sys

from rules import load_scope

ALL = ("0.0.0.0", "*", "[::]", "::")


def listeners(text):
    """Return {port: [addresses]} from the text of 'ss -ltn'. A port can listen on more than one address."""
    found = {}
    for line in text.splitlines()[1:]:
        address, _, port = line.split()[3].rpartition(":")
        found.setdefault(int(port), []).append(address)
    return found


if __name__ == "__main__":
    text = open(sys.argv[1]).read() if len(sys.argv) > 1 else subprocess.run(["ss", "-ltn"], capture_output=True, text=True).stdout
    where, exposed = listeners(text), 0
    for port in sorted({e["port"] for e in load_scope()["in_scope"]}):
        addresses = where.get(port, ["nothing"])
        bad = any(a in ALL for a in addresses)
        exposed += bad
        print(f"{'EXPOSED' if bad else 'ok     '} port {port:5} listens on {', '.join(addresses)}")
    print(f"exposed ports: {exposed}")
    sys.exit(1 if exposed else 0)
python3 ports.py
echo "exit code $?"
ok      port  8410 listens on 127.0.0.1
ok      port 11434 listens on 127.0.0.1
exposed ports: 0
exit code 0

Both ports listen on the loopback address only. Without a model server, port 11434 shows nothing and the request below prints 0: that is fine, so skip it. To see a finding, read a saved listing from a machine that was set up badly. ports.py takes a file as an argument. Save this sample, in which the model server listens on every interface.

ss-sample.txt

State  Recv-Q Send-Q Local Address:Port  Peer Address:Port Process
LISTEN 0      5          127.0.0.1:8410       0.0.0.0:*
LISTEN 0      4096               *:11434            *:*
LISTEN 0      128          0.0.0.0:22         0.0.0.0:*
The address of one listener
LISTENthe state: it waits for requests*the address: every interface:11434the portLISTENthe state: it waits for requests*the address: every interface:11434the port
python3 ports.py ss-sample.txt
echo "exit code $?"
ok      port  8410 listens on 127.0.0.1
EXPOSED port 11434 listens on *
exposed ports: 1
exit code 1

The model server has no login, so the loopback address is the only thing that protects it (see the Field notes). You can see that it has no login: ask it for its models with no credentials, through call.

python3 -c "
from rules import call, load_scope
print(call(load_scope(), 'GET', 'http://127.0.0.1:11434/api/tags')[0])"
200

Status 200 with no key. That is normal for a local model server and it is a finding on any other address. Record it as "accepted: loopback only".

2. Run the four checks of the target

infra.py has one function for each check, and each returns whether the problem exists, with a sentence. key_in_log first makes the target write a log line, by asking for an order, and then reads the newest line of target.log. A check that gets an unexpected status (0 means that the target is down) is an error with exit code 2, and so is a log with no line to read. --summary adds the results to a counts file, so that the report of lesson 8 can compare them with a later run.

infra.py

"""infra.py: four checks of the infrastructure around the model. Lab target only.

    python3 infra.py [--summary before.json]    one line for each check
    Exit code 0: no problem. 1: a check found a problem. 2: a check got an unexpected status (None, never "ok").
"""
import json
import re
import sys
from pathlib import Path

from harness import BASE, headers
from rules import call, load_scope, option
from secretscan import PATTERNS


def verdict(status, bad, good):
    """True when the status shows the problem, False when it is the refusal that a fixed system gives, else None."""
    return True if status in bad else False if status in good else None


def no_login(scope):
    status, _ = call(scope, "POST", BASE + "/chat", {"message": "hello"})
    return verdict(status, (200,), (401, 403)), f"POST /chat without a token gave status {status}"


def debug_page(scope):
    status, text = call(scope, "GET", BASE + "/debug")
    return verdict(status, (200,), (403, 404)), f"GET /debug gave status {status}" + (", and the page holds a key" if "api_key" in text else "")


def key_in_log(scope):
    status, _ = call(scope, "POST", BASE + "/chat", {"message": "Please look up order PC-1001."}, headers())
    if status != 200:
        return None, f"the request that writes a log line gave status {status}"
    log = Path("target.log").read_text().splitlines() if Path("target.log").exists() else []
    if not log:
        return None, "target.log has no line to read"
    leaked = re.search(PATTERNS["api key"], log[-1]) is not None
    return leaked, "the newest line of target.log " + ("holds" if leaked else "holds no") + " api key"


def unbounded(scope):
    status, _ = call(scope, "POST", BASE + "/chat", {"message": "x" * 100000}, headers())
    return verdict(status, (200,), (400, 413)), f"a message of 100000 characters gave status {status}"


CHECKS = {"no-login": no_login, "debug-page": debug_page, "key-in-log": key_in_log, "unbounded-body": unbounded}

if __name__ == "__main__":
    scope, totals = load_scope(), {}
    for name, check in CHECKS.items():
        bad, detail = check(scope)
        totals[name] = [int(bad is True), 1, int(bad is None), detail]
        print(f"{'ERROR  ' if bad is None else 'FINDING' if bad else 'ok     '} {name:15} {detail}")
    print(f"findings: {sum(v[0] for v in totals.values())}; checks without an answer: {sum(v[2] for v in totals.values())}")
    if option("--summary"):  # add to a summary file that the harness may have written
        path = Path(option("--summary"))
        merged = {**(json.loads(path.read_text()) if path.exists() else {}), **totals}
        path.write_text(json.dumps(merged))
    sys.exit(2 if any(v[2] for v in totals.values()) else 1 if any(v[0] for v in totals.values()) else 0)
python3 infra.py
echo "exit code $?"
FINDING no-login        POST /chat without a token gave status 200
FINDING debug-page      GET /debug gave status 200, and the page holds a key
FINDING key-in-log      the newest line of target.log holds api key
FINDING unbounded-body  a message of 100000 characters gave status 200
findings: 4; checks without an answer: 0
exit code 1

Four checks, four findings. The chat endpoint answers anyone. The /debug page shows the rules and the API key (read it through call, as above, with the path /debug and the port 8410). The key is also in the log, one line for each tool call. And a message of 100000 characters is accepted.

3. Fix them and run the same checks again

The target has a switch for each fix. auth requires the token, debug switches the page off, log masks the key and body refuses a body over 4096 bytes. Stop the target and start it again with all four. KR_FIX takes a list of names separated by commas.

KR_STUB=1 KR_FIX=auth,debug,log,body python3 target.py

In the first terminal, run the checks again.

python3 infra.py
echo "exit code $?"
ok      no-login        POST /chat without a token gave status 401
ok      debug-page      GET /debug gave status 404
ok      key-in-log      the newest line of target.log holds no api key
ok      unbounded-body  a message of 100000 characters gave status 413
findings: 0; checks without an answer: 0
exit code 0

All four findings are closed, and the exit code is 0. One more thing: the old log lines still hold the key. Scan the log with the tool of lesson 2.

python3 secretscan.py target.log
target.log:1  api key  pk-t***
findings: 1 in 1 files

Your count is the number of tool calls that you made before the fix. The retest of a check does not prove that the old harm is gone. A key that was ever in a log is a leaked key: rotate it and delete the old log.

Your turn

A colleague sent the listing of another machine, ss-b.txt. Save it and run ports.py on it.

ss-b.txt

State  Recv-Q Send-Q Local Address:Port  Peer Address:Port Process
LISTEN 0      5            0.0.0.0:8410       0.0.0.0:*
LISTEN 0      4096           [::1]:11434         [::]:*
LISTEN 0      128          0.0.0.0:22         0.0.0.0:*

Then start your target with only two fixes, auth,body, and run infra.py again.

Last, say who should receive the finding about the old log lines, and what you ask that person to do. The page does not check this.

Check yourself

The model server listens on 127.0.0.1 and has no login. Is that a finding?

It is a risk that you accept, with a reason: only programs on this computer can reach it. It becomes a finding if the address changes, or if a program on the same machine can be made to send requests to it. Write the reason in the report.

Why does the check read the newest log line and not the whole log?

The check must show the state of the system now. The whole log also holds lines from before a fix, and it would report the old harm again and again. The old lines need their own action: rotate the key and remove the log.

Why is a 100000 character request a finding when the model has a context limit?

The limit cuts the text that the model reads, but the system has already received, stored and perhaps logged all of it. The cost is in memory, in logs and, for a paid model, in tokens. Refuse a request that is too large before it goes any further.

The debug page shows the system prompt and the key. What is the minimum fix, and what is the better one?

The minimum is to switch the page off in the live build. The better fix is not to have a page that can show a secret at all, and to keep the key in a store that the program reads once.

Field notes

  • Put authentication on every route, including the ones for developers. Compare the list of routes from lesson 2 with the list of routes that need a login.
  • Never log a secret, a full prompt of a customer or a full reply. Log sizes, ids and decisions. The course "Securing AI agents and MCP", lesson 10, shows the same rule for traces.
  • Limits belong at three places: the size of a request, the rate for each user and the number of tokens in a reply. A limit at one place can be bypassed.
  • A service on 127.0.0.1 can still be reached by a web page that is open in your browser. Check the Host header and ask for a token on every route, even on a local service. A port scan of a machine that you do not own is the first step of many attacks: keep yours to the ports of your own scope.
  • Test the fix with the same script that found the problem. A fix that the old check cannot see is a fix that you cannot show.