#!/usr/bin/env bash
# Local penetration testing lab. Everything binds to 127.0.0.1.
# Never point the scanner at a system you do not own or have written permission to test.
set -euo pipefail

mkdir -p lab && cd lab

cat > lab_app.py <<'APP'
"""A small web application with deliberate flaws (vulnerable) and with fixes (secure)."""
import hashlib
import hmac
import html
import json
import secrets
import sqlite3
import sys
import time
from http.cookies import SimpleCookie
from http.server import BaseHTTPRequestHandler, HTTPServer
from urllib.parse import parse_qs, urlparse

SECURE = len(sys.argv) > 1 and sys.argv[1] == "secure"
PORT = 8081 if SECURE else 8080
ADMIN_PASSWORD = sys.argv[2] if len(sys.argv) > 2 else "admin"
MAX_FAILED_LOGINS = 5
PBKDF2_ITERATIONS = 600000   # OWASP-recommended work factor when PBKDF2-HMAC-SHA256 is required
LOCKOUT_SECONDS = 900        # failed attempts are forgotten after this window

db = sqlite3.connect(":memory:", check_same_thread=False)
db.executescript("""
create table products (id integer primary key, name text, price integer);
insert into products values (1,'Starter plan',19),(2,'Team plan',49),(3,'Business plan',199);
create table invoices (id integer primary key, owner text, amount integer);
insert into invoices values (1,'alice',19),(2,'bob',49),(3,'carol',199);
create table users (name text primary key, password text, role text);
""")


def store(password):
    """Vulnerable: plain text. Secure: PBKDF2 with a random salt per password, stored as salt$hash."""
    if not SECURE:
        return password
    salt = secrets.token_bytes(16)
    return salt.hex() + "$" + hashlib.pbkdf2_hmac("sha256", password.encode(), salt, PBKDF2_ITERATIONS).hex()


def check(password, stored):
    if not SECURE:
        return hmac.compare_digest(password, stored)
    salt_hex, digest = stored.split("$")
    attempt = hashlib.pbkdf2_hmac("sha256", password.encode(), bytes.fromhex(salt_hex), PBKDF2_ITERATIONS).hex()
    return hmac.compare_digest(attempt, digest)


for user, password, role in (("admin", ADMIN_PASSWORD, "admin"), ("alice", "alice-lab-pass", "user"),
                             ("bob", "bob-lab-pass", "user"), ("carol", "carol-lab-pass", "user")):
    db.execute("insert into users values (?, ?, ?)", (user, store(password), role))

sessions = {}     # session token -> user name, kept on the server
failures = {}     # client address -> times of recent failed logins. Lab only: in memory, per address


class Handler(BaseHTTPRequestHandler):
    # The vulnerable banner names a product version. BaseHTTPRequestHandler also appends
    # the real Python version of the machine running the lab, in both applications.
    server_version = "LabServer" if SECURE else "LabServer/2.3.1"

    def log_message(self, *args):
        pass

    def send(self, code, body, kind="text/html", extra=None):
        data = body.encode()
        self.send_response(code)
        self.send_header("Content-Type", kind + "; charset=utf-8")
        self.send_header("Content-Length", str(len(data)))
        if SECURE:
            self.send_header("Content-Security-Policy", "default-src 'self'")
            self.send_header("X-Content-Type-Options", "nosniff")
            self.send_header("X-Frame-Options", "DENY")
        for key, value in (extra or {}).items():
            self.send_header(key, value)
        self.end_headers()
        self.wfile.write(data)

    def current_user(self):
        """Identity comes only from the server-side session, never from a request header."""
        cookie = SimpleCookie(self.headers.get("Cookie", ""))
        token = cookie["sid"].value if "sid" in cookie else ""
        return sessions.get(token)

    def role(self, user):
        row = db.execute("select role from users where name = ?", (user,)).fetchone()
        return row[0] if row else None

    def do_GET(self):
        u = urlparse(self.path)
        q = parse_qs(u.query)
        user = self.current_user()
        if u.path == "/search":
            term = q.get("q", [""])[0]
            try:
                if SECURE:
                    rows = db.execute("select name, price from products where name like ?", (f"%{term}%",)).fetchall()
                else:
                    rows = db.execute(f"select name, price from products where name like '%{term}%'").fetchall()
            except sqlite3.Error as error:
                return self.send(500, "search failed" if SECURE else f"Database error: {error}")
            return self.send(200, json.dumps(rows), "application/json")
        if u.path == "/hello":
            name = q.get("name", ["guest"])[0]
            return self.send(200, f"<p>Hello {html.escape(name) if SECURE else name}</p>")
        if u.path == "/invoice":
            if not user:
                return self.send(401, "sign in first")
            row = db.execute("select owner, amount from invoices where id = ?", (q.get("id", ["0"])[0],)).fetchone()
            if not row:
                return self.send(404, "not found")
            if SECURE and row[0] != user:
                return self.send(403, "forbidden")
            return self.send(200, json.dumps({"owner": row[0], "amount": row[1]}), "application/json")
        if u.path == "/admin/users":
            if SECURE and self.role(user) != "admin":
                return self.send(403, "forbidden")
            rows = db.execute("select name, role, password from users").fetchall()
            return self.send(200, json.dumps(rows), "application/json")
        if not SECURE and u.path == "/backup.sql":
            dump = "\n".join(db.iterdump())
            return self.send(200, dump, "text/plain")
        if not SECURE and u.path == "/.git/HEAD":
            return self.send(200, "ref: refs/heads/main", "text/plain")
        return self.send(200, "<p>home</p>") if u.path == "/" else self.send(404, "not found")

    def do_POST(self):
        path = urlparse(self.path).path
        length = int(self.headers.get("Content-Length", 0))
        form = parse_qs(self.rfile.read(length).decode())
        if path == "/admin/price":
            if self.role(self.current_user()) != "admin":
                return self.send(403, "forbidden")
            db.execute("update products set price = ? where id = ?", (form.get("price", ["0"])[0], form.get("id", ["0"])[0]))
            return self.send(200, "price updated")
        if path != "/login":
            return self.send(404, "not found")
        name = form.get("name", [""])[0]
        password = form.get("password", [""])[0]
        address = self.client_address[0]
        recent = [t for t in failures.get(address, []) if time.time() - t < LOCKOUT_SECONDS]
        failures[address] = recent
        if SECURE and len(recent) >= MAX_FAILED_LOGINS:
            return self.send(429, "too many attempts")
        row = db.execute("select password from users where name = ?", (name,)).fetchone()
        if row and check(password, row[0]):
            if SECURE:
                # Random identifier per login. The lab has no TLS, so the Secure attribute is
                # shown in the response header only; a browser would not return it over HTTP.
                token = secrets.token_urlsafe(32)
                cookie = f"sid={token}; HttpOnly; Secure; SameSite=Strict"
            else:
                token = "sid-" + name          # predictable on purpose
                cookie = f"sid={token}"
            sessions[token] = name
            failures[address] = []          # a successful login clears the count
            return self.send(200, "welcome", extra={"Set-Cookie": cookie})
        failures[address].append(time.time())
        return self.send(401, "invalid")


HTTPServer(("127.0.0.1", PORT), Handler).serve_forever()
APP

cat > mini_pentest.py <<'SCAN'
"""A teaching scanner. It checks only what is written here. A clean result proves nothing more."""
import json
import math
import socket
import sys
import urllib.error
import urllib.parse
import urllib.request

BASE = sys.argv[1]
ADMIN_PASSWORD_GUESS = "admin"
WRONG_ATTEMPTS = 12


def call(path, data=None, headers=None):
    body = urllib.parse.urlencode(data).encode() if data is not None else None
    request = urllib.request.Request(BASE + path, data=body, headers=headers or {})
    try:
        with urllib.request.urlopen(request, timeout=10) as reply:
            return reply.status, reply.read().decode(), dict(reply.headers)
    except urllib.error.HTTPError as error:
        return error.code, error.read().decode(), dict(error.headers)


def roundup(value):
    integer = int(round(value * 100000))
    return integer / 100000.0 if integer % 10000 == 0 else (math.floor(integer / 10000) + 1) / 10.0


def base_score(vector):
    m = dict(part.split(":") for part in vector.split("/")[1:])
    changed = m["S"] == "C"
    weight = {"H": 0.56, "L": 0.22, "N": 0.0}
    iss = 1 - (1 - weight[m["C"]]) * (1 - weight[m["I"]]) * (1 - weight[m["A"]])
    impact = 7.52 * (iss - 0.029) - 3.25 * (iss - 0.02) ** 15 if changed else 6.42 * iss
    privileges = {"N": 0.85, "L": 0.68 if changed else 0.62, "H": 0.5 if changed else 0.27}[m["PR"]]
    exploitability = (8.22 * {"N": 0.85, "A": 0.62, "L": 0.55, "P": 0.2}[m["AV"]] * {"L": 0.77, "H": 0.44}[m["AC"]]
                      * privileges * {"N": 0.85, "R": 0.62}[m["UI"]])
    if impact <= 0:
        return 0.0
    total = impact + exploitability
    return roundup(min(1.08 * total if changed else total, 10))


def rating(score):
    return "Info" if score == 0 else "Low" if score < 4 else "Medium" if score < 7 else "High" if score < 9 else "Critical"


findings, passed = [], []


def finding(name, vector, evidence):
    findings.append((name, "CVSS:3.1/" + vector, evidence))


host, port = urllib.parse.urlparse(BASE).hostname, urllib.parse.urlparse(BASE).port
open_ports = []
for candidate in (8080, 8081):
    with socket.socket() as probe:
        probe.settimeout(1)
        if probe.connect_ex((host, candidate)) == 0:
            open_ports.append(candidate)
print("open ports in the lab range:", open_ports)

# Banner and headers
status, body, headers = call("/")
banner = headers.get("Server", "")
if any(ch.isdigit() for ch in banner):
    finding("Server banner states a version", "AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:N/A:N", banner)
missing = [h for h in ("Content-Security-Policy", "X-Content-Type-Options", "X-Frame-Options") if h not in headers]
if missing:
    finding("Protective security headers missing", "AV:N/AC:L/PR:N/UI:R/S:U/C:L/I:L/A:N", ", ".join(missing))

# Files that should not be public
status, body, _ = call("/backup.sql")
if status == 200 and "INSERT INTO" in body:
    finding("Database backup downloadable, including user records", "AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:N/A:N",
            f"{body.count('INSERT INTO')} rows of data in /backup.sql")
status, body, _ = call("/.git/HEAD")
if status == 200:
    finding("Repository metadata exposed", "AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:N/A:N", f"/.git/HEAD returned: {body.strip()}")

# Admin function without a session
status, body, _ = call("/admin/users")
if status == 200:
    finding("Admin user list readable without signing in", "AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:N/A:N",
            f"{len(json.loads(body))} user records returned, with stored passwords")
else:
    passed.append(f"admin user list refused without a session (HTTP {status})")

# Search: error leak and SQL injection that reads another table
status, body, _ = call("/search?q=" + urllib.parse.quote("'"))
if status == 500 and "error" in body.lower():
    finding("Database error message leaked", "AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:N/A:N", body[:60])
union = "zzz' union select name, password from users --"
status, body, _ = call("/search?q=" + urllib.parse.quote(union))
leaked = [row[0] for row in json.loads(body)] if status == 200 else []
if "admin" in leaked:
    finding("SQL injection reads the users table", "AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:N/A:N",
            f"search returned {len(leaked)} user records")
else:
    passed.append("search did not return user records for the injection string")

# Output handling: a script element returned unescaped in an HTML response
payload = "<script>labmarker7x()</script>"
status, body, headers = call("/hello?name=" + urllib.parse.quote(payload))
if payload in body and "text/html" in headers.get("Content-Type", ""):
    finding("Reflected cross-site scripting", "AV:N/AC:L/PR:N/UI:R/S:C/C:L/I:L/A:N",
            "script element returned unescaped in an HTML page (not executed in a browser)")
else:
    passed.append("script element was escaped in the HTML response")

# Sign in as an ordinary user and keep her cookie
status, _, headers = call("/login", {"name": "alice", "password": "alice-lab-pass"})
alice_cookie = headers.get("Set-Cookie", "").split(";")[0]
if status != 200 or not alice_cookie:
    raise SystemExit("scanner error: could not sign in as the lab user alice")
absent = [flag for flag in ("HttpOnly", "Secure", "SameSite") if flag.lower() not in headers.get("Set-Cookie", "").lower()]
if absent:
    finding("Session cookie lacks protective flags", "AV:N/AC:H/PR:N/UI:R/S:U/C:L/I:L/A:N", "missing " + ", ".join(absent))
else:
    passed.append("session cookie carries HttpOnly, Secure and SameSite")
own, _, _ = call("/invoice?id=1", headers={"Cookie": alice_cookie})
if own != 200:
    raise SystemExit("scanner error: alice could not read her own invoice")
others = [i for i in (2, 3) if call(f"/invoice?id={i}", headers={"Cookie": alice_cookie})[0] == 200]
spoofed = [i for i, owner in ((2, "bob"), (3, "carol"))
           if call(f"/invoice?id={i}", headers={"Cookie": alice_cookie, "X-User": owner})[0] == 200]
if others or spoofed:
    finding("Other users' invoices readable", "AV:N/AC:L/PR:L/UI:N/S:U/C:H/I:N/A:N",
            f"alice's session read invoices {sorted(set(others + spoofed))}")
else:
    passed.append("alice's session was refused invoices 2 and 3, also with a spoofed X-User header")
status, _, _ = call("/admin/price", {"id": "1", "price": "1"}, {"Cookie": alice_cookie})
if status == 200:
    finding("Ordinary user can change prices", "AV:N/AC:L/PR:L/UI:N/S:U/C:N/I:H/A:N", "alice changed a product price")
else:
    passed.append(f"alice was refused the price change (HTTP {status})")

# Default administrator password, and what it gives access to
status, _, headers = call("/login", {"name": "admin", "password": ADMIN_PASSWORD_GUESS})
if status == 200:
    admin_cookie = headers.get("Set-Cookie", "").split(";")[0]
    read, body, _ = call("/admin/users", headers={"Cookie": admin_cookie})
    write, _, _ = call("/admin/price", {"id": "3", "price": "1"}, {"Cookie": admin_cookie})
    finding("Default administrator password accepted", "AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:N",
            f"admin/admin signed in, read the user list (HTTP {read}) and changed a price (HTTP {write})")
else:
    passed.append("default administrator password was refused")

# Repeated wrong passwords
codes = [call("/login", {"name": "admin", "password": f"wrong{i}"})[0] for i in range(WRONG_ATTEMPTS)]
if 429 not in codes:
    finding("No limit on repeated failed logins", "AV:N/AC:H/PR:N/UI:N/S:U/C:L/I:L/A:N",
            f"{WRONG_ATTEMPTS} wrong passwords, never refused")
else:
    passed.append(f"login refused after {codes.index(429)} wrong passwords")

print(f"\nFindings against {BASE}: {len(findings)}")
for name, vector, evidence in sorted(findings, key=lambda f: (-base_score(f[1]), f[0])):
    score = base_score(vector)
    print(f"  {score:>4} {rating(score):8} {name} | {evidence} | {vector}")
print("Checks that found nothing:", len(passed))
for line in passed:
    print("  ok:", line)
SCAN

cat > scoping.py <<'SCOPE'
"""An invented effort model for scoping a test. The inputs are illustrations, not industry prices."""
ITEMS = {  # item: (tester days per item, count in scope)
    "Planning and reporting": (2, 1),
    "Web application": (4, 2),
    "API": (3, 1),
    "Network range": (2, 1),
    "Cloud account": (3, 1),
}
KNOWLEDGE_FACTOR = {"black box": 1.0, "grey box": 0.85, "white box": 0.8}
ASSUMED_DAY_RATE = 1200
for name, (days_each, count) in ITEMS.items():
    print(f"  {name}: {days_each} x {count} = {days_each * count} days")
base_days = sum(days_each * count for days_each, count in ITEMS.values())
print("scoping model: tester days", base_days)
for name, factor in KNOWLEDGE_FACTOR.items():
    print(f"{name} {base_days * factor:.1f} days")
print("at an assumed day rate of", ASSUMED_DAY_RATE, "the grey box test costs",
      round(base_days * KNOWLEDGE_FACTOR["grey box"] * ASSUMED_DAY_RATE))
assert base_days == 18
SCOPE

APP_PID=""
cleanup() {
  if [[ -n "$APP_PID" ]]; then kill "$APP_PID" 2>/dev/null || true; fi
}
trap cleanup EXIT
trap 'exit 130' INT
trap 'exit 143' TERM

port_is_free() {
  python3 -c "import socket,sys; s=socket.socket(); sys.exit(0 if s.connect_ex(('127.0.0.1', int(sys.argv[1]))) != 0 else 1)" "$1"
}

start_app() {   # start_app MODE PORT [ADMIN_PASSWORD]
  if ! port_is_free "$2"; then echo "Port $2 is already in use. Stop that program and run again." >&2; exit 1; fi
  python3 lab_app.py "$1" ${3:+"$3"} &
  APP_PID=$!
  for _ in $(seq 1 50); do
    if ! port_is_free "$2"; then return 0; fi
    sleep 0.1
  done
  echo "The lab application did not start on port $2." >&2; exit 1
}

stop_app() {
  kill "$APP_PID" 2>/dev/null || true
  wait "$APP_PID" 2>/dev/null || true
  APP_PID=""
}

echo "python: $(python3 -c 'import sys; print(sys.version.split()[0])')"
echo "RUN 1: vulnerable application"
start_app vulnerable 8080
python3 mini_pentest.py http://127.0.0.1:8080
stop_app

echo "RUN 2: first round of fixes, default password still in place"
start_app secure 8081
python3 mini_pentest.py http://127.0.0.1:8081
stop_app

echo "RUN 3: default password replaced"
start_app secure 8081 "a-long-random-lab-passphrase-41"
python3 mini_pentest.py http://127.0.0.1:8081
stop_app

python3 scoping.py
echo "All three scans and the scoping model completed."
