Capstone 1: Scope, Rules of Engagement and Recon
The capstone is a full assessment of one application, from the first email to the final report, done the way the Penetration Testing course teaches and written up so that the defenders can act on it. The target is Lab Library, a small book-lending web application written for this course and deliberately full of mistakes. You start it yourself, in your sandbox, on 127.0.0.1; nothing else is ever touched. This lesson covers the engagement's paperwork and the reconnaissance. Capstone 2 confirms the findings, scores them, fixes them and retests; the mini project turns everything into the report.
Before anything else: authorization
An assessment without written permission is an attack, whatever the intention; the authorization and scope lesson explains the law behind that sentence. In this capstone, the application is yours (you start it from the lesson's code) and the "client" is fictional, but you still write the documents, because writing them is the skill. In the scenario, a small library's IT volunteer asks for a test before the app goes live and signs the rules of engagement below.
The rules of engagement
| Item | Value |
|---|---|
| Client | Lab Library (fictional), contact: the IT volunteer, it@lab.test |
| Target | the Lab Library application: main app on port 8080 and anything else the same process exposes; in the sandbox, 127.0.0.1 only |
| Deployment assumption | in production the app will listen on all interfaces of srv01.lab.test (10.10.0.10); findings are rated for that deployment |
| In scope | all web functionality, unauthenticated and as the test accounts; source code review (white-box) |
| Test accounts | alice / lab-alice-pw and bob / lab-bob-pw (members); no librarian account is provided |
| Out of scope | denial of service, the host system, any other address |
| Data | synthetic only; any real-looking personal data found is reported, not copied |
| Window | your lab hours; stop and report at once if anything outside the scope responds |
| Deliverables | findings with evidence and CVSS v3.1 scores, fixes, retest results, the final report |
Two lines carry most of the weight. The deployment assumption makes the ratings meaningful: in the sandbox everything is on loopback, but a finding is rated for how the app will really run. And "anything else the same process exposes" brings a second port into scope, which recon is about to find; without that line, you would have to stop and ask before testing it.
Reconnaissance
Recon answers three questions: what is listening, what is it, and how does it behave at its edges. The session below writes the application, starts it (main app on 8080, a second listener on 9090), and runs five recon steps against 127.0.0.1 only. Read app.py afterwards for the white-box part; for now, look at it from the outside, as the recon would.
cat > app.py <<'PY'
import hashlib, hmac, html, json, posixpath, sqlite3
from http.cookies import SimpleCookie
from urllib.parse import parse_qs
from cryptography.hazmat.primitives.kdf.scrypt import Scrypt
FIXED = False # the retest flips this to True
SECRET = b"lab-signing-key-0001" # lab-only; leaked by the debug page
FILES = {"public/help.txt": b"Opening hours: 9-17. Ask at the desk.\n",
"config/app.env": b"SECRET_KEY=lab-signing-key-0001\nDB_PATH=:memory:\n"}
def hash_pw(pw, salt=b"lab-fixed-salt01"): # real code: a new salt per user
if not FIXED:
return hashlib.sha256(pw.encode()).hexdigest() # unsalted, fast
return "scryptquot; + Scrypt(salt=salt, length=32, n=2**14, r=8, p=1).derive(pw.encode()).hex()
def make_db():
db = sqlite3.connect(":memory:")
db.executescript("""
CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT, pw TEXT, role TEXT);
CREATE TABLE books (id INTEGER PRIMARY KEY, title TEXT, author TEXT);
CREATE TABLE loans (id INTEGER PRIMARY KEY, user_id INTEGER, book_id INTEGER, due TEXT);
INSERT INTO books VALUES (1, 'Networks', 'Tanaka'), (2, 'Ciphers', 'Okafor'), (3, 'Kernels', 'Lind');
INSERT INTO loans VALUES (1, 1, 2, '2026-02-01'), (2, 2, 1, '2026-02-03'), (3, 2, 3, '2026-02-05');
""")
for uid, name, pw, role in [(1, "alice", "lab-alice-pw", "member"), (2, "bob", "lab-bob-pw", "member"),
(3, "admin", "lab-admin-pw", "librarian")]:
db.execute("INSERT INTO users VALUES (?, ?, ?, ?)", (uid, name, hash_pw(pw), role))
return db
DB = make_db()
def sign(name):
return name + "." + hmac.new(SECRET, name.encode(), "sha256").hexdigest()[:16]
def current_user(environ):
c = SimpleCookie(environ.get("HTTP_COOKIE", "")).get("session")
if not c or "." not in c.value:
return None
name = c.value.rsplit(".", 1)[0]
if not hmac.compare_digest(c.value, sign(name)):
return None
return DB.execute("SELECT id, name, role FROM users WHERE name = ?", (name,)).fetchone()
def app(environ, start_response):
path, method = environ["PATH_INFO"], environ["REQUEST_METHOD"]
query = parse_qs(environ.get("QUERY_STRING", ""))
headers = [("Content-Type", "text/html; charset=utf-8")]
if FIXED:
headers += [("Content-Security-Policy", "default-src 'self'"), ("X-Content-Type-Options", "nosniff")]
def reply(status, body, extra=()):
start_response(status, headers + list(extra))
return [body.encode() if isinstance(body, str) else body]
if path == "/":
return reply("200 OK", "<h1>Lab Library</h1><form action=/search><input name=q></form>")
if path == "/robots.txt":
return reply("200 OK", "User-agent: *\nDisallow: /download\n")
if path == "/search":
q = query.get("q", [""])[0]
try:
if FIXED:
rows = DB.execute("SELECT title, author FROM books WHERE title LIKE ?", (f"%{q}%",)).fetchall()
else:
rows = DB.execute(f"SELECT title, author FROM books WHERE title LIKE '%{q}%'").fetchall()
except sqlite3.Error as e:
return reply("500 Internal Server Error", "error" if FIXED else f"database error: {e}")
shown = html.escape(q) if FIXED else q
items = "".join(f"<li>{html.escape(str(t))} ({html.escape(str(a))})</li>" for t, a in rows)
return reply("200 OK", f"<p>Results for {shown}</p><ul>{items}</ul>")
if path == "/login" and method == "POST":
size = int(environ.get("CONTENT_LENGTH") or 0)
form = parse_qs(environ["wsgi.input"].read(size).decode())
name, pw = form.get("user", [""])[0], form.get("password", [""])[0]
row = DB.execute("SELECT pw FROM users WHERE name = ?", (name,)).fetchone()
if not row or not hmac.compare_digest(row[0], hash_pw(pw)):
return reply("401 Unauthorized", "invalid user name or password")
flags = "; HttpOnly; Secure; SameSite=Lax" if FIXED else ""
return reply("200 OK", f"welcome {name}", [("Set-Cookie", f"session={sign(name)}; Path=/{flags}")])
if path.startswith("/api/loans/"):
user = current_user(environ)
if user is None:
return reply("401 Unauthorized", "sign in first")
loan_id = path.rsplit("/", 1)[1]
sql = "SELECT id, user_id, book_id, due FROM loans WHERE id = ?"
args = (loan_id,)
if FIXED and user[2] != "librarian":
sql, args = sql + " AND user_id = ?", (loan_id, user[0])
row = DB.execute(sql, args).fetchone()
if not row:
return reply("404 Not Found", "no such loan")
return reply("200 OK", json.dumps(dict(zip(("id", "user_id", "book_id", "due"), row))))
if path == "/download":
target = posixpath.normpath("public/" + query.get("file", [""])[0])
if FIXED and not target.startswith("public/"):
return reply("403 Forbidden", "not allowed")
if target in FILES:
return reply("200 OK", FILES[target])
return reply("404 Not Found", "no such file")
return reply("404 Not Found", "not found")
def debug_app(environ, start_response): # the "metrics" port, meant for developers only
if FIXED or environ["PATH_INFO"] != "/debug":
start_response("404 Not Found", [("Content-Type", "text/plain")])
return [b"not found"]
start_response("200 OK", [("Content-Type", "application/json")])
return [json.dumps({"version": "0.9-lab", "secret_key": SECRET.decode(), "db": ":memory:"}).encode()]
PY
cat > serve.py <<'PY'
import threading
from wsgiref.simple_server import make_server, WSGIRequestHandler
from app import app, debug_app
class Quiet(WSGIRequestHandler):
def log_message(self, *args):
pass
debug = make_server("127.0.0.1", 9090, debug_app, handler_class=Quiet)
threading.Thread(target=debug.serve_forever, daemon=True).start()
make_server("127.0.0.1", 8080, app, handler_class=Quiet).serve_forever()
PY
python3 serve.py 2>serve.err &
for i in $(seq 50); do curl -s -o /dev/null http://127.0.0.1:8080/ && break; sleep 0.1; done
echo "== 1. ports (scope: 127.0.0.1 only)"
nmap -sT -p 22,80,443,8080,8443,9090 127.0.0.1 | grep -E '^[0-9]+/tcp'
echo "== 2. headers of the main app"
curl -s -D - -o /dev/null http://127.0.0.1:8080/ | grep -v '^Date' | tr -d '\r'
echo "== 3. robots.txt"
curl -s http://127.0.0.1:8080/robots.txt
echo "== 4. what answers on 9090? (a short list of common paths)"
for p in / /status /metrics /debug; do
printf '%-9s %s\n' "$p" "$(curl -s -o /dev/null -w '%{http_code}' http://127.0.0.1:9090$p)"
done
curl -s http://127.0.0.1:9090/debug; echo
echo "== 5. how the app reacts to a quote in the search"
curl -s "http://127.0.0.1:8080/search?q=net" ; echo
curl -s "http://127.0.0.1:8080/search?q=%27" ; echo
kill %1== 1. ports (scope: 127.0.0.1 only)
22/tcp closed ssh
80/tcp closed http
443/tcp closed https
8080/tcp open http-proxy
8443/tcp closed https-alt
9090/tcp open zeus-admin
== 2. headers of the main app
HTTP/1.0 200 OK
Server: WSGIServer/0.2 CPython/3.12.3
Content-Type: text/html; charset=utf-8
Content-Length: 62
== 3. robots.txt
User-agent: *
Disallow: /download
== 4. what answers on 9090? (a short list of common paths)
/ 404
/status 404
/metrics 404
/debug 200
{"version": "0.9-lab", "secret_key": "lab-signing-key-0001", "db": ":memory:"}
== 5. how the app reacts to a quote in the search
<p>Results for net</p><ul><li>Networks (Tanaka)</li></ul>
database error: unrecognized token: "'"
What recon found, step by step:
- Two open ports among the six checked: 8080 (the app) and 9090, which nobody mentioned. Nmap's service names (
http-proxy,zeus-admin) are only guesses from its port table; the second listener is identified by talking to it. - The headers reveal the server software (
WSGIServer/0.2 CPython/3.12.3) and lackContent-Security-Policy,X-Content-Type-Optionsand the rest of the security headers. Low severity alone, but it raises the impact of any injection. robots.txtasks crawlers to stay away from/download. It is not a security control; for a tester it is a map of what the developers consider sensitive.- Port 9090 returns 404 for most paths but
/debuganswers, with the application's secret signing key in the response. This is the most serious observation of the recon, and you would note it immediately: in a real engagement, a leaked secret is often reported to the client before the report, as the rules of engagement allow. - A single quote in the search box produces a raw SQLite error message. Errors that echo the database's parser are the classic sign of SQL built by concatenation.
From recon to a test plan
Recon produces an attack-surface map, and the map produces the test plan for Capstone 2:
| Surface | Observation | Planned tests | Course lesson |
|---|---|---|---|
GET /search?q= |
quote causes a database error; the term is echoed in the page | SQL injection (UNION), reflected XSS | SQLi, XSS |
POST /login, session cookie |
cookie set without flags | cookie flags; session forgery if the key leaks | cookies |
GET /api/loans/<id> |
numeric ids | access to other users' loans (IDOR) | IDOR |
GET /download?file= |
listed in robots.txt; takes a file name | path traversal | path traversal |
:9090/debug |
leaks the signing key | confirm impact (forged session) | HTTP messages |
| source code | white-box review | password storage, error handling | password hashing |
| all responses | no security headers | headers and CSP | CSP |
How recon itself is detected
The blue-team half of recon is worth a paragraph in the report: an Nmap connect scan leaves one connection per probed port in the server's logs (the sandbox's serve.py silences its log, which is itself a finding: no access log means no detection), a path list against /status, /metrics and /debug leaves a burst of 404s from one source, and a quote in a search parameter followed by a 500 error is a pattern every web application firewall and SIEM rule set looks for. The client should be able to see your recon in their logs; if they can't, say so (A09:2025).
Pitfalls
- Testing before the rules of engagement are signed. Even in a lab, write them first; the habit is the point.
- Trusting Nmap's service names.
zeus-adminon 9090 is a guess from a port list; the service was a Python debug endpoint. - Exploring the leak further than needed. The debug page proves the key leaks; you don't need to dump more to show the impact.
Practice
1. Which recon observation would you report to the client before the final report, and why?
The signing key on :9090/debug. Anyone who can reach the port can forge a session for any user, including the librarian, so the client should rotate the key and close the port now, not in two weeks when the report arrives.
2. Write one line for the report's "method" section describing step 4 accurately.
"Port 9090 was identified during a TCP connect scan of the in-scope host; four common administrative paths were requested (/, /status, /metrics, /debug); /debug returned HTTP 200 with application configuration including the session signing key."
Test yourself
Why does the rules-of-engagement line 'anything else the same process exposes' matter?
- It allows denial of service
- It brings the unexpected port 9090 into scope, so it can be tested without stopping to ask
- It allows scanning other hosts
- It is boilerplate
What does the raw SQLite error after a single quote suggest?
- The database is down
- The search builds SQL by string concatenation
- The app uses an ORM
- Nothing
How should the findings be rated, given that everything runs on 127.0.0.1 in the sandbox?
- As local-only (AV:L)
- For the documented production deployment, where the app listens on the network
- Not at all
- As physical (AV:P)
What does robots.txt tell a tester?
- Which pages are protected
- Which paths the developers would rather crawlers skipped, a hint of what they find sensitive
- Which pages are out of scope
- Nothing