Who is asking, every time?
The grades app answered the printer because it came from the right network. A bank does not pay out because a letter has the right postmark.
It asks who you are on every payment. Your app can do the same.
The one rule
Warning
Everything in this module happens on the lab machine that is your own. Forging a token for a system 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 put an identity-aware proxy in front of an app so that every request needs a signed identity.
Key words
| Word | What it means | Example |
|---|---|---|
| Identity-aware proxy | a front door that checks who is asking before passing a request on | |
| Identity provider | the service that signs people in and vouches for them | |
| Token | signed proof of who someone is, for a short time | |
| Claim | one fact inside a token | "groups": ["staff"] |
| Policy | the rules for who may reach what | |
| Enforcement point | the place where a decision is carried out |
The cells students fill in are left blank in this preview.
Starter
Have a go
Starter
3 questionsThe proxy decides, the app serves
An identity-aware proxy stands in front of the app. People reach the proxy, never the app.
For each request it checks the token's signature, its expiry and its audience, then the policy for the page. Only then does it pass the request on, naming the user.
The policy for grades
| Page | Group needed | amy (staff) | ben (student) | carla (staff, admin) |
|---|---|---|---|---|
| /grades | staff | allow | deny | allow |
| /admin/export | admin | deny | deny | allow |
The cells students fill in are left blank in this preview.
Try it: the policy as code
POLICY = {"/grades": "staff", "/admin/export": "admin"}
people = {"amy": ["staff"], "ben": ["student"], "carla": ["staff", "admin"]}
for user, groups in people.items():
for path, need in POLICY.items():
answer = "allow" if need in groups else "deny"
print(user, path, answer)
# Give ben the group "staff". Which line changes?
Make a free account to save your work and track your progress.
Check
Have a go
Check
3 questionsMake sure the campus is running
cd ~/zt && zt up; zt start db db python3 db.py && zt start grades grades python3 app.pyShown here, not run. Press Start lab to type it into your own lab’s terminal.
Write the sign-in service, part 1
mkdir -p ~/zt && printf '%s\n' '"""idp.py init | issue USER [MINUTES]: the sign-in service. It signs short-lived identity tokens."""' 'import base64, hashlib, hmac, json, os, secrets, sys, time' '' 'USERS = {"amy": ["staff"], "ben": ["student"], "carla": ["staff", "admin"]}' 'b64 = lambda data: base64.urlsafe_b64encode(data).rstrip(b"=").decode()' 'if sys.argv[1] == "init":' ' with open(os.open("idp.key", os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600), "w") as key:' ' key.write(secrets.token_hex(32))' ' print("idp: a new signing key in idp.key, readable by its owner alone")' ' sys.exit()' 'user, minutes, now = sys.argv[2], int((sys.argv[3:] or [10])[0]), int(time.time())' 'claims = {"sub": user, "groups": USERS[user], "aud": "grades", "iat": now, "exp": now + minutes * 60}' 'signed = b64(json.dumps({"alg": "HS256", "typ": "JWT"}).encode()) + "." + b64(json.dumps(claims).encode())' > ~/zt/idp.pyShown here, not run. Press Start lab to type it into your own lab’s terminal.
Write the sign-in service, part 2
printf '%s\n' 'sig = hmac.new(open("idp.key", "rb").read(), signed.encode(), hashlib.sha256).digest()' 'open(user + ".tok", "w").write(signed + "." + b64(sig))' 'print("idp:", user, claims["groups"], "for", minutes, "minutes, in", user + ".tok")' >> ~/zt/idp.pyShown here, not run. Press Start lab to type it into your own lab’s terminal.
Make its signing key
cd ~/zt && python3 idp.py init && stat -c "%A %U %n" idp.keyShown here, not run. Press Start lab to type it into your own lab’s terminal.
Write the proxy, part 1
mkdir -p ~/zt && printf '%s\n' '"""proxy.py [--posture] [--mtls] [--report]: the identity-aware proxy on 8000, in front of grades.' 'Every request needs a signed identity token. --posture also asks for a healthy device (lesson 3),' '--mtls calls grades over mutual TLS (lesson 5), --report lets refused requests through and logs them (lesson 6)."""' 'import base64, hashlib, hmac, json, ssl, sys, time, urllib.error, urllib.request' 'from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer' '' 'POLICY = {"/grades": "staff", "/admin/export": "admin"}' 'KEY = open("idp.key", "rb").read()' 'POSTURE, MTLS, REPORT = "--posture" in sys.argv, "--mtls" in sys.argv, "--report" in sys.argv' 'if POSTURE:' ' import posture' 'unb64 = lambda text: base64.urlsafe_b64decode(text + "=" * (-len(text) % 4))' '' '' 'def identity(header):' ' """The claims of a good token and no reason, or no claims and the reason it is refused."""' > ~/zt/proxy.pyShown here, not run. Press Start lab to type it into your own lab’s terminal.
Write the proxy, part 2
printf '%s\n' ' parts = header.removeprefix("Bearer ").split(".")' ' if not header.startswith("Bearer "):' ' return None, "no token"' ' if not len(parts) == 3:' ' return None, "not a token"' ' if not json.loads(unb64(parts[0])).get("alg") == "HS256":' ' return None, "wrong algorithm"' ' good = hmac.new(KEY, (parts[0] + "." + parts[1]).encode(), hashlib.sha256).digest()' ' if not hmac.compare_digest(good, unb64(parts[2])):' ' return None, "bad signature"' ' claims = json.loads(unb64(parts[1]))' ' if claims["exp"] < time.time():' ' return None, "expired"' ' if not claims.get("aud") == "grades":' ' return None, "wrong audience"' ' return claims, None' '' '' 'def decide(headers, path):' ' """The status, the user, the device and the reason, for one request."""' ' claims, why = identity(headers.get("Authorization", ""))' ' if why:' ' return 401, "-", "-", why' ' if path not in POLICY:' >> ~/zt/proxy.pyShown here, not run. Press Start lab to type it into your own lab’s terminal.
Write the proxy, part 3
printf '%s\n' ' return 404, claims["sub"], "-", "no such page"' ' if POLICY[path] not in claims["groups"]:' ' return 403, claims["sub"], "-", "needs group " + POLICY[path]' ' device, problems = posture.check(headers.get("X-Posture", "")) if POSTURE else ("-", [])' ' if problems:' ' return 403, claims["sub"], device, "device: " + ", ".join(problems)' ' return 200, claims["sub"], device, "ok"' '' '' 'def upstream(path, user):' ' tls = ssl.create_default_context(cafile="ca.crt") if MTLS else None' ' if MTLS:' ' tls.load_cert_chain("proxy.crt", "proxy.key")' ' url = ("https://10.30.0.10:8443" if MTLS else "http://10.30.0.10:8080") + path' ' try:' ' with urllib.request.urlopen(urllib.request.Request(url, headers={"X-User": user}), context=tls) as answer:' ' return answer.status, answer.read()' ' except urllib.error.HTTPError as refused:' ' return refused.code, refused.read()' '' '' >> ~/zt/proxy.pyShown here, not run. Press Start lab to type it into your own lab’s terminal.
Write the proxy, part 4
printf '%s\n' 'class Proxy(BaseHTTPRequestHandler):' ' def log_message(self, *args):' ' pass' '' ' def do_GET(self):' ' status, user, device, why = decide(self.headers, self.path)' ' decision = "allow" if status == 200 else "would-deny" if REPORT else "deny"' ' if status == 200 or REPORT:' ' status, body = upstream(self.path, user)' ' else:' ' body = json.dumps({"error": why}).encode()' ' self.send_response(status)' ' self.send_header("Content-Length", str(len(body)))' ' self.end_headers()' ' self.wfile.write(body)' ' print(json.dumps({"time": int(time.time()), "client": self.client_address[0], "user": user, "device": device,' ' "path": self.path, "decision": decision, "status": status, "reason": why}), flush=True)' '' '' 'ThreadingHTTPServer(("0.0.0.0", 8000), Proxy).serve_forever()' >> ~/zt/proxy.pyShown here, not run. Press Start lab to type it into your own lab’s terminal.
Start the proxy and sign three people in
cd ~/zt && zt start proxy proxy python3 proxy.py && python3 idp.py issue amy && python3 idp.py issue ben && python3 idp.py issue carlaShown here, not run. Press Start lab to type it into your own lab’s terminal.
Ask as nobody, amy, ben and carla
zt laptop python3 get.py http://10.30.0.5:8000/grades; for u in amy ben; do zt laptop python3 get.py http://10.30.0.5:8000/grades token=$u.tok; done; for u in amy carla; do zt laptop python3 get.py http://10.30.0.5:8000/admin/export token=$u.tok; doneShown here, not run. Press Start lab to type it into your own lab’s terminal.
A token lasts minutes, not months
Each token here lasts ten minutes. A stolen token is then useful for minutes, and signing in again is when the identity provider can say no.
Make one that has already expired, and change a token as an attacker would.
Write the forger
mkdir -p ~/zt && printf '%s\n' '"""forge.py TOKEN-FILE: put admin in a token and keep its old signature, as an attacker would."""' 'import base64' 'import json' 'import sys' '' 'head, body, sig = open(sys.argv[1]).read().split(".")' 'claims = json.loads(base64.urlsafe_b64decode(body + "=" * (-len(body) % 4)))' 'claims["groups"] = ["staff", "admin"]' 'body = base64.urlsafe_b64encode(json.dumps(claims).encode()).rstrip(b"=").decode()' 'open("forged.tok", "w").write(head + "." + body + "." + sig)' 'print("forged.tok:", claims["sub"], claims["groups"], "with the old signature")' > ~/zt/forge.pyShown here, not run. Press Start lab to type it into your own lab’s terminal.
Try an expired token and a forged one
cd ~/zt && python3 idp.py issue amy -1 && mv amy.tok old.tok && python3 idp.py issue amy && python3 forge.py ben.tok && zt laptop python3 get.py http://10.30.0.5:8000/grades token=old.tok; zt laptop python3 get.py http://10.30.0.5:8000/admin/export token=forged.tokShown here, not run. Press Start lab to type it into your own lab’s terminal.
Check
Have a go
Check
3 questionsA common mistake
Warning
Many people think a proxy protects an app just by standing in front of it. It protects it only if it is the only way in. While the app still answers the network, anyone can go round the proxy.
Go round the proxy from the printer
zt printer python3 get.py http://10.30.0.10:8080/admin/export X-User:carlaShown here, not run. Press Start lab to type it into your own lab’s terminal.
The fix, and how it is seen
The app believed an X-User header that anyone can type. The fix is to let only the proxy reach the app, by firewall in lesson 4 and by certificate in lesson 5.
The proxy writes one line for every decision. A burst of 401s from one address, or a bad signature at all, is an alert.
Read the proxy's decisions
cd ~/zt && tail -n 4 logs/proxy.logShown here, not run. Press Start lab to type it into your own lab’s terminal.
Assignment: check a token like the proxy
Check a token the way the proxy does.
verify(token, key, now) returns (claims, None) for a good token, or (None, reason), checking in order: three parts ("not a token"), alg is HS256 ("wrong algorithm"), the HMAC-SHA256 of head.body ("bad signature"), exp after now ("expired"), aud is "grades" ("wrong audience"). allowed(claims, path, policy) is True when the path is in the policy and its group is in the claims.
import base64
import hashlib
import hmac
import json
def unb64(text):
return base64.urlsafe_b64decode(text + "=" * (-len(text) % 4))
def verify(token, key, now):
# token is "head.body.signature", each part base64url. Return (claims, None) when good,
# or (None, reason). Check in this order: three parts ("not a token"), alg is HS256
# ("wrong algorithm"), the HMAC-SHA256 of "head.body" ("bad signature"), exp is after now
# ("expired"), aud is "grades" ("wrong audience").
return None, "not written yet"
def allowed(claims, path, policy):
# policy: {"/grades": "staff"}. True when the path is listed and its group is in claims["groups"].
return False
Make a free account to save your work and track your progress.
Exit quiz
Have a go