A printer that could read the grades
A college joins its sites with a VPN, and staff connect from home through it. Once inside, every device trusts every other.
One day an attacker takes over an old printer. From the printer they read every student's grades, and nothing stops them.
The one rule
Warning
Everything in this module happens on the lab machine that is your own. Testing a network you do not own needs the owner's written permission. In the UK, without it, it can break the Computer Misuse Act 1990.
Quick check: the rule
Have a go
Quick check: the rule
3 questionsBy the end of this lesson
Note
I can show how one weak device on a flat network reaches every service.
Key words
| Word | What it means |
|---|---|
| Perimeter | the edge between inside and outside a network |
| Flat network | a network where every device can reach every other |
| Implicit trust | trust given for being inside, with no check |
| Lateral movement | an attacker moving from one machine to the next |
| Blast radius | everything one stolen foothold can reach |
| Zero trust | checking every request, wherever it comes from |
The cells students fill in are left blank in this preview.
Starter
Have a go
Starter
3 questionsA VPN joins whole networks
The old design is a castle with a moat. The firewall at the edge keeps strangers out, and anyone inside is trusted.
A VPN extends the inside. In the lab's tunnel, AllowedIPs names a whole network, 10.2.0.0/24. Whatever reaches the gateway goes on to every host behind it.
Does the gateway filter anything?
sudo ip netns exec gwB sysctl net.ipv4.ip_forward; sudo ip netns exec gwB nft list ruleset | wc -lShown here, not run. Press Start lab to type it into your own lab’s terminal.
Check
Have a go
Check
3 questionsA college network of your own
You will not touch the lab's two sites. Beside them a script called zt builds a college network on one switch, 10.30.0.0/24, like a site behind a VPN.
On it are a proxy (.5), the grades app (.10, port 8080) and its database (.11, port 5432). A staff laptop is .21 and an old printer .50. The grades app allows any request from 10.30.0.0/24. Being on the network is its only check: that is implicit trust.
Write the campus builder, part 1
mkdir -p ~/zt && printf '%s\n' '"""zt up | down | status, zt start NAME NODE CMD, zt stop [NAME], zt NODE CMD:' 'a college network of namespaces. Services and commands run as student."""' 'import os, pwd, signal, subprocess, sys, time' '' 'NODES = {"proxy": "10.30.0.5", "grades": "10.30.0.10", "db": "10.30.0.11",' ' "laptop": "10.30.0.21", "printer": "10.30.0.50"}' 'HOME, RUN = "/home/student/zt", "/run/zt"' 'ME = pwd.getpwnam("student")' 'AS_ME = ["setpriv", "--reuid=student", "--regid=student", "--init-groups", "--"]' '' '' 'def ip(*args):' ' subprocess.run(["ip", *args], check=True)' '' '' 'def up():' ' if os.path.exists("/run/netns/zt-lan"):' ' return print("zt: already up")' ' ip("netns", "add", "zt-lan")' ' ip("-n", "zt-lan", "link", "add", "sw", "up", "type", "bridge")' ' for node, addr in NODES.items():' ' ns = "zt-" + node' ' ip("netns", "add", ns)' ' ip("-n", ns, "link", "set", "lo", "up")' > ~/zt/campus.pyShown here, not run. Press Start lab to type it into your own lab’s terminal.
Write the campus builder, part 2
printf '%s\n' ' ip("link", "add", "lan0", "netns", ns, "type", "veth", "peer", node, "netns", "zt-lan")' ' ip("-n", "zt-lan", "link", "set", node, "master", "sw", "up")' ' ip("-n", ns, "addr", "add", addr + "/24", "dev", "lan0")' ' ip("-n", ns, "link", "set", "lan0", "up")' ' print("zt: up:", *NODES)' '' '' 'def running():' ' found = {}' ' for f in os.listdir(RUN) if os.path.isdir(RUN) else []:' ' node, pid = open(RUN + "/" + f).read().split()' ' if os.path.exists("/proc/" + pid):' ' found[f[:-4]] = (node, int(pid))' ' return found' '' '' 'def start(name, node, command):' ' stop(name)' ' os.makedirs(RUN, exist_ok=True)' ' os.makedirs(HOME + "/logs", exist_ok=True)' ' os.chown(HOME + "/logs", ME.pw_uid, ME.pw_gid)' ' log = open(f"{HOME}/logs/{name}.log", "a")' ' os.chown(log.name, ME.pw_uid, ME.pw_gid)' >> ~/zt/campus.pyShown here, not run. Press Start lab to type it into your own lab’s terminal.
Write the campus builder, part 3
printf '%s\n' ' child = subprocess.Popen(["ip", "netns", "exec", "zt-" + node, *AS_ME, *command], cwd=HOME,' ' stdout=log, stderr=log, stdin=subprocess.DEVNULL, start_new_session=True)' ' time.sleep(1)' ' if child.poll() is None:' ' open(f"{RUN}/{name}.pid", "w").write(f"{node} {child.pid}")' ' return print(f"zt: {name} started in {node}")' ' print(f"zt: {name} stopped at once, see logs/{name}.log")' '' '' 'def stop(name=None):' ' for one, (node, pid) in running().items():' ' if name in (None, one):' ' os.killpg(pid, signal.SIGTERM)' ' os.remove(f"{RUN}/{one}.pid")' '' '' 'def main(args):' ' if args == ["install"]:' ' me = open(os.path.realpath(__file__)).read()' ' open("/usr/local/bin/zt", "w").write("#" + chr(33) + "/usr/bin/python3" + chr(10) + me)' ' os.chmod("/usr/local/bin/zt", 0o755)' ' return print("zt: installed")' >> ~/zt/campus.pyShown here, not run. Press Start lab to type it into your own lab’s terminal.
Write the campus builder, part 4
printf '%s\n' ' if not os.geteuid() == 0:' ' os.execvp("sudo", ["sudo", sys.executable, os.path.realpath(__file__), *args])' ' if args[:1] == ["up"]:' ' up()' ' elif args[:1] == ["down"]:' ' stop()' ' for ns in ["zt-lan"] + ["zt-" + n for n in NODES]:' ' subprocess.run(["ip", "netns", "del", ns], stderr=subprocess.DEVNULL)' ' elif args[:1] == ["start"] and len(args) > 3:' ' start(args[1], args[2], args[3:])' ' elif args[:1] == ["stop"]:' ' stop(*args[1:2])' ' elif args[:1] and args[0] in NODES:' ' os.chdir(HOME)' ' os.execvp("ip", ["ip", "netns", "exec", "zt-" + args[0], *AS_ME, *args[1:]])' ' elif not os.path.exists("/run/netns/zt-lan"):' ' print("zt: not up (zt up)")' ' else:' ' services = running()' ' for node, addr in NODES.items():' ' print(f"{node:8} {addr:11}", *[s for s, (n, p) in services.items() if n == node])' '' '' 'main(sys.argv[1:])' >> ~/zt/campus.pyShown here, not run. Press Start lab to type it into your own lab’s terminal.
Make the zt command and build the campus
sudo python3 ~/zt/campus.py install && zt up && zt statusShown here, not run. Press Start lab to type it into your own lab’s terminal.
Write the database
mkdir -p ~/zt && printf '%s\n' '"""db.py: a stand-in database on port 5432. It sends the grades to whoever connects."""' 'import json' 'import socketserver' 'import time' '' 'GRADES = [{"student": "ben", "module": "networks", "mark": 64},' ' {"student": "dina", "module": "networks", "mark": 71},' ' {"student": "eli", "module": "databases", "mark": 58}]' '' '' 'class Query(socketserver.StreamRequestHandler):' ' def handle(self):' ' self.rfile.readline()' ' self.wfile.write(json.dumps(GRADES).encode() + bytes([10]))' ' print(time.strftime("%H:%M:%S"), "query from", self.client_address[0], flush=True)' '' '' 'socketserver.ThreadingTCPServer.allow_reuse_address = True' 'socketserver.ThreadingTCPServer(("0.0.0.0", 5432), Query).serve_forever()' > ~/zt/db.pyShown here, not run. Press Start lab to type it into your own lab’s terminal.
Write the grades app, part 1
mkdir -p ~/zt && printf '%s\n' '"""app.py: the grades app on 8080. It trusts the campus network."""' 'import ipaddress, json, socket, time' 'from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer' '' 'CAMPUS = ipaddress.ip_network("10.30.0.0/24")' 'ADMINS, CALLERS, TLS = ["carla"], ["proxy"], False' '' '' 'def grades():' ' with socket.create_connection(("10.30.0.11", 5432), timeout=2) as db:' ' db.sendall(b"SELECT * FROM grades" + bytes([10]))' ' return json.loads(db.makefile().readline())' '' '' 'class App(BaseHTTPRequestHandler):' ' def log_message(self, *args):' ' pass' '' ' def answer(self, code, body, peer, user):' ' data = json.dumps(body).encode()' ' self.send_response(code)' ' self.end_headers()' ' self.wfile.write(data)' ' print(time.strftime("%H:%M:%S"), self.client_address[0], "peer=" + peer, "user=" + user,' ' self.path, code, flush=True)' '' ' def do_GET(self):' > ~/zt/app.pyShown here, not run. Press Start lab to type it into your own lab’s terminal.
Write the grades app, part 2
printf '%s\n' ' peer, user = "-", self.headers.get("X-User", "-")' ' if TLS:' ' peer = dict(x[0] for x in self.connection.getpeercert()["subject"])["commonName"]' ' if peer not in CALLERS:' ' return self.answer(403, {"error": "caller " + peer + " may not call grades"}, peer, "-")' ' elif ipaddress.ip_address(self.client_address[0]) not in CAMPUS:' ' return self.answer(403, {"error": "not on the campus network"}, peer, user)' ' if self.path == "/grades":' ' return self.answer(200, {"user": user, "grades": grades()}, peer, user)' ' if self.path == "/admin/export" and user in ADMINS:' ' return self.answer(200, {"user": user, "export": "all 3 records, with home addresses"}, peer, user)' ' self.answer(403, {"error": "admins only"}, peer, user)' '' '' 'if __name__ == "__main__":' ' ThreadingHTTPServer(("0.0.0.0", 8080), App).serve_forever()' >> ~/zt/app.pyShown here, not run. Press Start lab to type it into your own lab’s terminal.
Write a small web client, part 1
mkdir -p ~/zt && printf '%s\n' '"""get.py URL [token=F] [posture=F] [cert=NAME] [ca=F] [Header:value]: one request and its answer."""' 'import ssl, sys, urllib.error, urllib.request' '' 'request, opt = urllib.request.Request(sys.argv[1]), {}' 'for arg in sys.argv[2:]:' ' if "=" in arg:' ' opt.update([arg.split("=", 1)])' ' else:' ' request.add_header(*arg.split(":", 1))' 'if "token" in opt:' ' request.add_header("Authorization", "Bearer " + open(opt["token"]).read().strip())' 'if "posture" in opt:' ' request.add_header("X-Posture", open(opt["posture"]).read().strip())' 'tls = ssl.create_default_context(cafile=opt.get("ca")) if sys.argv[1].startswith("https") else None' 'if "cert" in opt:' ' tls.load_cert_chain(opt["cert"] + ".crt", opt["cert"] + ".key")' 'try:' ' answer = urllib.request.urlopen(request, timeout=5, context=tls)' 'except urllib.error.HTTPError as refused:' ' answer = refused' 'except OSError as failed:' > ~/zt/get.pyShown here, not run. Press Start lab to type it into your own lab’s terminal.
Write a small web client, part 2
printf '%s\n' ' answer = print("no answer:", getattr(failed, "reason", failed))' 'if answer:' ' print(answer.status, answer.reason, answer.read().decode()[:300])' >> ~/zt/get.pyShown here, not run. Press Start lab to type it into your own lab’s terminal.
Start both, and ask from the laptop
cd ~/zt && zt start db db python3 db.py && zt start grades grades python3 app.py && zt laptop python3 get.py http://10.30.0.10:8080/gradesShown here, not run. Press Start lab to type it into your own lab’s terminal.
Try it: what can the printer reach?
flows = {"vpn": ["laptop", "printer", "grades", "db"], "printer": ["grades", "db"],
"grades": ["db"], "laptop": [], "db": []}
seen = ["printer"]
for host in seen:
for nxt in flows[host]:
if nxt not in seen:
seen.append(nxt)
print("from the printer an attacker reaches:", seen[1:])
# Empty the printer's list, as a firewall would. What does it reach now?
Make a free account to save your work and track your progress.
Check
Have a go
Check
3 questionsWrite a small port scanner
mkdir -p ~/zt && printf '%s\n' '"""scan.py: from the node it runs in, try every campus address on a few ports and list what answers."""' 'import socket' 'import threading' '' 'HOSTS = {"10.30.0.5": "proxy", "10.30.0.10": "grades", "10.30.0.11": "db",' ' "10.30.0.21": "laptop", "10.30.0.50": "printer"}' 'PORTS = [22, 5432, 8000, 8080, 8443]' 'found = []' '' '' 'def knock(host, port):' ' try:' ' socket.create_connection((host, port), timeout=1).close()' ' found.append((host, port))' ' except OSError:' ' pass' '' '' 'tries = [threading.Thread(target=knock, args=(h, p)) for h in HOSTS for p in PORTS]' 'for t in tries:' ' t.start()' 'for t in tries:' ' t.join()' 'for host in HOSTS:' ' ports = sorted(p for h, p in found if h == host)' ' if ports:' ' print(f"{HOSTS[host]:8} {host:11}", *ports)' 'print(len(found), "open of", len(tries), "tried")' > ~/zt/scan.pyShown here, not run. Press Start lab to type it into your own lab’s terminal.
From the printer: scan, then take
zt printer python3 scan.py; zt printer python3 get.py http://10.30.0.10:8080/grades; echo hello | zt printer nc -N 10.30.0.11 5432Shown here, not run. Press Start lab to type it into your own lab’s terminal.
A common mistake
Warning
Many people think a VPN makes a network safe, because the tunnel is encrypted. Encryption protects packets on the way. It says nothing about what a device may reach once inside, so a flat network still hands everything to one foothold.
The fix, and how it is seen
The fix is the rest of this module. Check who is asking on every request, check their device, and let each service take only the callers it needs.
It is seen in the logs today. A printer never needs the grades, so any line from 10.30.0.50 in the app or database log is an alert.
Find the printer in the logs
cd ~/zt && grep -h 10.30.0.50 logs/grades.log logs/db.logShown here, not run. Press Start lab to type it into your own lab’s terminal.
Assignment: measure the blast radius
Measure how far one foothold reaches.
flat_flows(hosts) returns every ordered pair of different hosts, sorted: on a flat network anyone reaches anyone. blast_radius(flows, start) returns the sorted hosts an attacker on start reaches by following flows one hop at a time, without start itself.
def flat_flows(hosts):
# Every ordered pair (a, b) of different hosts: on a flat network, anyone reaches anyone.
# Return them sorted.
return []
def blast_radius(flows, start):
# flows: {"printer": ["grades", "db"], ...}, who can open a connection to whom.
# Return the sorted hosts an attacker on start can reach, directly or one hop at a time.
# Do not include start itself.
return []
Make a free account to save your work and track your progress.
Exit quiz
Have a go