Lesson 01 · 40 minutes
Scope the test and write the rules of engagement
- Write a scope file that says what may be tested, when, and how much
- Make a program refuse every request that the scope does not allow
- Stop a test on a stop word, on a spent budget or on repeated errors
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 colleague says: "The chatbot of the other team is slow today. Run a scanner on it and see what happens." Nobody has asked the other team, and nothing is written down. Your lead answers for you: no written scope, no test. You write the rules for your lab target, and you build a checker that refuses any request that the rules do not allow.
The idea
A red-team test is an attack that someone asked for. Paper, not skill, makes it legal and safe. A real job gives you three documents:
| Document | What it says |
|---|---|
| Permission | The owner of the system allows the test, in writing, and names who may test. |
| Scope | What is in: hosts, ports, paths, kinds of test. What is out. |
| Rules of engagement | Hours, request budget, what to do when something breaks, how to stop, who to call. |
In this course you are the owner and the tester, so the permission is one sentence in your own file. You still write it down, because the habit is the lesson. The scope goes into a file that code reads: a scope in a document gets forgotten, and a scope that a program enforces does not.
- Test case → rules.py: one planned request
- rules.py → STOP-NOW: stop file there? then it stops
- rules.py → Target (8410): in scope: sent and counted
- rules.py → Model server (11434): in scope: GET /api/tags only
- rules.py → Other hosts and ports (blocked): not in scope
Three ideas help you to design the checker. A redirect is a new request. A program that followed "go to another address" would leave the scope unchecked, so call does not: you get the 3xx status and decide by hand. It also ignores proxy settings, which could send a request elsewhere. Match exactly. The names localhost and 127.0.0.1 usually mean the same machine, but a name can point somewhere else tomorrow. Only plain http is allowed, and each port has its own paths and methods. An address with a user name, a backslash or path parameters (;x) is refused, so that the checker and the sender cannot read it in two ways. A query string (?x=1) is allowed. The fix for a refusal is a better scope, not a looser checker. Fail closed. A request that the scope does not name is refused, not allowed.
Worked example
1. Write the scope
scope.json is a JSON file (a text format for data: lists in [ ], objects in { }). Save it in the lab folder. In: one entry for each port, and a path that one entry allows is not allowed on the other port. Out: everything else. The hours cover the whole day: the lab is yours.
scope.json
{
"system": "Pinecrest Outdoors chat assistant, lab copy",
"permission": "I own this computer and this program. This file is my written permission, dated 2026-11-21.",
"in_scope": [
{"host": "127.0.0.1", "port": 8410, "paths": ["/chat", "/health", "/debug"], "methods": ["GET", "POST"]},
{"host": "127.0.0.1", "port": 11434, "paths": ["/api/tags"], "methods": ["GET"]}
],
"out_of_scope": {
"categories": [],
"notes": ["every other host, port and path", "the model weights", "any machine that is not mine"]
},
"hours": {"from": "00:00", "to": "23:59"},
"stop_word": "STOP-NOW",
"max_requests": 500,
"max_errors": 5
}2. Write the checker
rules.py holds the rules as code. New words: urlparse splits an address into scheme, host, port and path. A class that inherits from Exception is a new kind of error, here Refused. Path(...).exists() tests whether a file exists. sys.argv is the list of words that you typed after python3. option reads a word such as --scope scope.json from that list: the other programs of the course import it.
refusal returns the reason for a refusal, or None. stop_reason says whether the test must stop. A refusal that no program catches ends that program with exit code 2 and the line stopped: reason, so a script sees a broken run and not a result. call is the only function that sends a request: it asks both first, and it counts what it sends in the file budget.txt, so that every program spends one budget. check tests planned requests without sending them. The stop word is a file name: the owner tells you the word, you create that file in the folder where you run the tools, and your next request stops.
rules.py
"""rules.py: the rules of engagement in code. Every request of this course goes through call().
python3 rules.py check draft.json [--scope scope.json] [--at HH:MM] [--runs N]
python3 rules.py used how much of the budget is spent
python3 rules.py reset start a new budget (only when the owner gives you one)
"""
import http.client
import json
import os
import sys
import time
import urllib.error
import urllib.request
from pathlib import Path
from urllib.parse import urlparse
BUDGET = Path("budget.txt") # requests sent: a file, so that every program adds to it
FAILED = [0] # failed requests in a row (no answer, 5xx, 401, 403, 429), in this program only
class Refused(Exception):
"""A request that the rules do not allow. It is never sent."""
class NoRedirect(urllib.request.HTTPRedirectHandler):
def redirect_request(self, *args, **kwargs):
return None # a redirect is a new request that the rules have not checked
def refused_exit(kind, why, trace):
"""An uncaught Refused ends the program with exit code 2 and the reason, not with a traceback."""
if kind is not Refused:
return sys.__excepthook__(kind, why, trace)
print(f"stopped: {why}")
sys.stdout.flush()
os._exit(2)
sys.excepthook = refused_exit
# No redirect and no proxy: a request goes to the address that refusal() looked at, and nowhere else.
OPENER = urllib.request.build_opener(urllib.request.ProxyHandler({}), NoRedirect)
def used():
"""Return the number of requests sent so far."""
return int(BUDGET.read_text()) if BUDGET.exists() else 0
def option(name, default=None):
"""Return the word that follows `name` on the command line, or `default`."""
return sys.argv[sys.argv.index(name) + 1] if name in sys.argv else default
def load_scope(path="scope.json"):
return json.load(open(path))
def refusal(scope, method, url, category=None, at=None):
"""Return why a request is refused, or None."""
u = urlparse(url)
if u.username or u.password or "\\" in url or u.params:
return "url" # a user name, a backslash or path parameters: two parsers may read the address in two ways
hosts = [e for e in scope["in_scope"] if e["host"] == u.hostname]
entries = [e for e in hosts if e["port"] == u.port]
if u.scheme != "http":
return "scheme"
if not hosts:
return "host"
if not entries:
return "port"
if u.path not in entries[0]["paths"]:
return "path"
if method not in entries[0]["methods"]:
return "method"
if (category or "").lower() in [c.lower() for c in scope["out_of_scope"]["categories"]]:
return "category"
start, end = scope["hours"]["from"], scope["hours"]["to"]
if at and not (start <= at <= end if start <= end else at >= start or at <= end): # "22:00" to "06:00" crosses midnight
return "hours"
return None
def stop_reason(scope, used, errors_in_row, stop_file_present):
"""Return why the test must stop now (stop word, budget or errors), or None."""
if stop_file_present:
return "stop word"
if used >= scope["max_requests"]:
return "budget"
if errors_in_row >= scope["max_errors"]:
return "errors"
return None
def call(scope, method, url, body=None, headers=None, category=None):
"""Send one request if the rules allow it. Return (status, text). Status 0 means no answer."""
why = refusal(scope, method, url, category, time.strftime("%H:%M")) \
or stop_reason(scope, used(), FAILED[0], Path(scope["stop_word"]).exists())
if why:
raise Refused(why)
data = json.dumps(body).encode() if body is not None else None
request = urllib.request.Request(url, data, {"Content-Type": "application/json", **(headers or {})}, method=method)
try:
with OPENER.open(request, timeout=180) as reply:
status, text = reply.status, reply.read().decode()
except urllib.error.HTTPError as error:
status, text = error.code, error.read().decode()
except (OSError, http.client.HTTPException): # no answer, or an answer that is not HTTP
status, text = 0, ""
BUDGET.write_text(str(used() + 1))
FAILED[0] = FAILED[0] + 1 if status in (0, 401, 403, 429) or status >= 500 else 0
return status, text
def check(draft, scope, at, runs):
"""Print one line for each draft request. Return 1 when any is refused or the budget is too small."""
refused = 0
for r in draft:
why = refusal(scope, r["method"], r["url"], r.get("category"), at)
refused += bool(why)
print(f"{'REFUSED' if why else 'ok '} {r['id']:12} {r['method']:7} {r['url']}" + (f" ({why})" if why else ""))
allowed = len(draft) - refused
need = allowed * runs
over = need > scope["max_requests"]
print(f"allowed {allowed}, refused {refused}; {need} requests needed, budget {scope['max_requests']}" + (" TOO MANY" if over else ""))
return 1 if refused or over else 0
if __name__ == "__main__":
args = sys.argv[1:]
if args[:1] == ["check"]:
sys.exit(check(json.load(open(args[1])), load_scope(option("--scope", "scope.json")),
option("--at", time.strftime("%H:%M")), int(option("--runs", 1))))
elif args[:1] == ["used"]:
print(f"requests used: {used()} of {load_scope()['max_requests']}")
elif args[:1] == ["reset"]:
BUDGET.unlink(missing_ok=True)
print("budget reset")
else:
print(__doc__)3. Check a draft
A colleague wrote twelve requests for a test. Save them as draft.json.
draft.json
[
{"id": "health", "method": "GET", "url": "http://127.0.0.1:8410/health"},
{"id": "chat-1", "method": "POST", "url": "http://127.0.0.1:8410/chat", "category": "Prompt Injection"},
{"id": "debug", "method": "GET", "url": "http://127.0.0.1:8410/debug"},
{"id": "admin", "method": "GET", "url": "http://127.0.0.1:8410/admin"},
{"id": "chat-delete", "method": "DELETE", "url": "http://127.0.0.1:8410/chat"},
{"id": "other-port", "method": "GET", "url": "http://127.0.0.1:8411/health"},
{"id": "by-name", "method": "GET", "url": "http://localhost:8410/health"},
{"id": "third-party", "method": "POST", "url": "http://198.51.100.7/chat", "category": "Prompt Injection"},
{"id": "tags", "method": "GET", "url": "http://127.0.0.1:11434/api/tags"},
{"id": "target-tags", "method": "GET", "url": "http://127.0.0.1:8410/api/tags"},
{"id": "secure", "method": "GET", "url": "https://127.0.0.1:8410/health"},
{"id": "generate", "method": "POST", "url": "http://127.0.0.1:11434/api/generate"}
]$? holds the exit code of the last command: 0 means success, and any other number means that the program found a problem or failed. The second line prints it.
python3 rules.py check draft.json
echo "exit code $?"ok health GET http://127.0.0.1:8410/health
ok chat-1 POST http://127.0.0.1:8410/chat
ok debug GET http://127.0.0.1:8410/debug
REFUSED admin GET http://127.0.0.1:8410/admin (path)
REFUSED chat-delete DELETE http://127.0.0.1:8410/chat (method)
REFUSED other-port GET http://127.0.0.1:8411/health (port)
REFUSED by-name GET http://localhost:8410/health (host)
REFUSED third-party POST http://198.51.100.7/chat (host)
ok tags GET http://127.0.0.1:11434/api/tags
REFUSED target-tags GET http://127.0.0.1:8410/api/tags (path)
REFUSED secure GET https://127.0.0.1:8410/health (scheme)
REFUSED generate POST http://127.0.0.1:11434/api/generate (path)
allowed 4, refused 8; 4 requests needed, budget 500
exit code 1Eight of twelve are refused, each for one rule (in brackets). other-port and by-name show the exact-match rule: port 8411 and the name localhost are not written in the scope. target-tags asks the target for a path that only the model server may serve. generate would use the model, and the scope allows only the list. The exit code is 1, so a script can stop on it.
4. Check the budget
The budget is the number of requests that you may send in all, over every program and run, until the owner gives you a new one. --runs is the number of repeats that you plan for each allowed request.
python3 rules.py check draft.json --runs 200 | tail -1allowed 4, refused 8; 800 requests needed, budget 500 TOO MANY5. Test the stop rule
stop_reason is a plain function, so you can test it with fixed numbers: the requests used, the failed requests in a row, and whether the stop file exists.
python3 -c "
from rules import load_scope, stop_reason
s = load_scope()
print(stop_reason(s, 499, 0, False), stop_reason(s, 500, 0, False), stop_reason(s, 10, 5, False), stop_reason(s, 10, 0, True))"None budget errors stop wordNow test the real thing: make the stop file, try one allowed request, delete the file. Nothing is sent, so the target need not run.
touch STOP-NOW
python3 -c "
from rules import call, load_scope, Refused
try:
call(load_scope(), 'GET', 'http://127.0.0.1:8410/health')
except Refused as why:
print('refused:', why)"
rm STOP-NOWrefused: stop word6. Test the redirect rule and the budget
This program starts a small server on port 8410 (stop your target first) that redirects every request to port 8411, which is not in scope. A call that followed the redirect would print (0, ''). It must print status 302.
python3 -c "
import threading
from http.server import BaseHTTPRequestHandler, HTTPServer
from rules import call, load_scope
class Redirect(BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(302)
self.send_header('Location', 'http://127.0.0.1:8411/health')
self.end_headers()
def log_message(self, *args):
pass
server = HTTPServer(('127.0.0.1', 8410), Redirect)
threading.Thread(target=server.serve_forever, daemon=True).start()
print(call(load_scope(), 'GET', 'http://127.0.0.1:8410/health'))"
python3 rules.py used
python3 rules.py reset(302, '')
requests used: 1 of 500
budget resetA different program read the count of 1 from budget.txt. reset deletes that file: run it only when the owner gives you a new budget (in your own lab, you may reset it when a lesson stops with the reason budget). Failed requests in a row (no answer, 5xx, 401, 403 or 429) are counted for one program only, and one program at a time may use the budget file: run one tool at a time.
Your turn
A colleague runs a second lab and gives you its rules in words. Write scope-b.json from them. There is no code to copy: use the format of your own scope.json.
- Host
127.0.0.1, ports 8412 and 8413 (one entry for each port), paths/askand/status, methods GET and POST. - The category "Unbounded Consumption" is out of scope.
- Hours 09:00 to 17:00. Stop word
HALT. At most 20 requests, and a stop after 3 failed requests in a row.
Save the colleague's plan as draft-b.json, then check it.
draft-b.json
[
{"id": "b1", "method": "GET", "url": "http://127.0.0.1:8412/status"},
{"id": "b2", "method": "POST", "url": "http://127.0.0.1:8412/ask", "category": "Prompt Injection"},
{"id": "b3", "method": "POST", "url": "http://127.0.0.1:8413/ask", "category": "Excessive Agency"},
{"id": "b4", "method": "GET", "url": "http://127.0.0.1:8412/admin"},
{"id": "b5", "method": "POST", "url": "http://127.0.0.1:8412/ask", "category": "Unbounded Consumption"},
{"id": "b6", "method": "PUT", "url": "http://127.0.0.1:8413/ask"},
{"id": "b7", "method": "GET", "url": "http://127.0.0.1:8414/status"},
{"id": "b8", "method": "POST", "url": "http://127.0.0.1:8413/ask", "category": "Sensitive Information Disclosure"}
]Run rules.py check on it with your scope file, at 10:00 and at 18:30, and once at 10:00 with --runs 6. Then call stop_reason with your scope.
Last, say which refusal at 10:00 you would take back to the owner as a question. The page does not check this.
Check yourself
Why does the checker refuse "localhost" when "127.0.0.1" is in scope?
A name can resolve to another address on another day. The checker matches the written text, and the owner decides what the scope says.
What does a request budget protect?
The target and its owners. A test without a limit can fill a log, exhaust a model quota or hide a real attack in the noise.
Why is the stop word a file name and not a message inside the chat?
A stop word must work when the system itself is unwell. A file on the tester's machine stops the next request whatever the target does.
Field notes
- Permission comes from someone who has the authority to give it. A cloud service or a model provider may forbid some tests in its terms: read them, and put the answer in the scope.
- A real scope names a contact for emergencies, and says what you do if you find real customer data: stop, do not copy it, and tell the contact. It also gives a reason for each item that is out of scope.
- Write hours as
HH:MM.fromlater thantomeans a window across midnight, such as22:00to06:00.