Easier to read with cream paper, a tint, more contrast or larger text? Choose your colours and text, once, for every page.

Free lesson

Device posture in the access decision

After this lesson: I can make an access decision refuse a device that fails a health check.

60 min lesson13 commandsWireGuard lab: build a VPN tunnel between two sites in your browser

A quick check that you are not a bot, then your own lab opens on the interactive lesson.

Already have an account? Sign in

The right person on the wrong laptop

Amy signs in properly, from a home laptop with no firewall and months without updates. Her password is right. The laptop may already belong to someone else.

A careful college asks about the device as well as the person.

The one rule

Warning

Everything in this module happens on the lab machine that is your own. Faking a device report to 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 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

By the end of this lesson

Note

I can make an access decision refuse a device that fails a health check.

Key words

WordWhat it means
Device posturehow healthy a device is right now
Device agenta program on the device that reports its health
Enrolmentregistering a device and giving it a key
Posture reportsigned facts about a device at one moment
Freshnesshow recent a report is
Conditional accessaccess that depends on the user and the device

The cells students fill in are left blank in this preview.

Starter

Have a go

Starter

3 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

A device reports its own health

An agent on the device reads facts the device can prove: its system version, whether its firewall is on, and when it last fetched updates.

It signs them with the key it was given at enrolment. The proxy checks the signature, the time and each fact, then decides.

The rules the proxy applies

FactRuleRefused as
timeno older than 120 secondsreport too old
osUbuntu 26.04os ... not allowed
firewallan input chain that drops by defaultfirewall off
updated_daysat most 14not updated for N days

The cells students fill in are left blank in this preview.

Try it: decide on a report

Code: python
report = {"os": "26.04", "firewall": False, "updated_days": 3, "age_seconds": 30}
problems = []
if report["age_seconds"] > 120:
    problems.append("report too old")
if not report["firewall"]:
    problems.append("firewall off")
if report["updated_days"] > 14:
    problems.append("not updated")
print("allow" if not problems else "deny: " + ", ".join(problems))
# Turn the firewall on and make updated_days 20. What is the answer now?

Make a free account to save your work and track your progress.

Check

Have a go

Check

3 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

Start the campus with a fresh token

Command
cd ~/zt && zt up; zt start db db python3 db.py && zt start grades grades python3 app.py && python3 idp.py issue amy

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Write the device agent, part 1

Command
mkdir -p ~/zt && printf '%s\n' '"""devagent.py enrol NAME | report NAME [MINUTES-AGO]: the device agent, run as root on the device.' 'It reads facts about this device and signs a report with the key the device was enrolled with."""' 'import base64' 'import hashlib' 'import hmac' 'import json' 'import os' 'import pwd' 'import secrets' 'import subprocess' 'import sys' 'import time' '' 'STUDENT = pwd.getpwnam("student")' '' '' 'def b64(data):' '    return base64.urlsafe_b64encode(data).rstrip(b"=").decode()' '' '' 'def firewall_on():' '    rules = json.loads(subprocess.run(["nft", "-j", "list", "ruleset"], capture_output=True, text=True).stdout)' '    chains = [x["chain"] for x in rules["nftables"] if "chain" in x]' '    return any(c.get("hook") == "input" and c.get("policy") == "drop" for c in chains)' '' '' 'def facts(name, minutes_ago):' '    release = dict(line.strip().split("=", 1) for line in open("/etc/os-release") if "=" in line)' > ~/zt/devagent.py

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Write the device agent, part 2

Command
printf '%s\n' '    updated = time.time() - os.path.getmtime("/var/lib/apt/lists")' '    return {"device": name, "time": int(time.time()) - minutes_ago * 60,' '            "os": release["VERSION_ID"].strip(chr(34)), "firewall": firewall_on(),' '            "updated_days": int(updated // 86400)}' '' '' 'def enrol(name):' '    os.makedirs("devices", exist_ok=True)' '    key = secrets.token_hex(32)' '    mine = os.open("devices/" + name + ".key", os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)' '    os.write(mine, key.encode())' '    os.close(mine)' '    known = json.load(open("enrolled.json")) if os.path.exists("enrolled.json") else {}' '    known[name] = key' '    shared = os.open("enrolled.json", os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)' '    os.write(shared, json.dumps(known).encode())' '    os.close(shared)' '    os.chown("enrolled.json", STUDENT.pw_uid, STUDENT.pw_gid)' '    print("devagent: enrolled", name, "with a key of its own")' '' '' >> ~/zt/devagent.py

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Write the device agent, part 3

Command
printf '%s\n' 'def report(name, minutes_ago):' '    body = b64(json.dumps(facts(name, minutes_ago)).encode())' '    key = open("devices/" + name + ".key", "rb").read()' '    open(name + ".posture", "w").write(body + "." + b64(hmac.new(key, body.encode(), hashlib.sha256).digest()))' '    print("devagent:", json.dumps(facts(name, minutes_ago)))' '' '' 'if sys.argv[1] == "enrol":' '    enrol(sys.argv[2])' 'else:' '    report(sys.argv[2], int(sys.argv[3]) if len(sys.argv) > 3 else 0)' >> ~/zt/devagent.py

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Write the proxy's device check, part 1

Command
mkdir -p ~/zt && printf '%s\n' '"""posture.py: the device check the proxy makes. A report must come from an enrolled device, be fresh, and be healthy."""' 'import base64' 'import hashlib' 'import hmac' 'import json' 'import time' '' 'MAX_AGE = 120' 'OS_ALLOWED = ["26.04"]' 'MAX_UPDATE_DAYS = 14' '' '' 'def unb64(text):' '    return base64.urlsafe_b64decode(text + "=" * (-len(text) % 4))' '' '' 'def check(header):' '    """The device name and a list of problems, empty when the device may be used."""' '    if "." not in header:' '        return "-", ["no report"]' '    body, sig = header.split(".", 1)' '    report = json.loads(unb64(body))' '    name = report.get("device", "-")' '    key = json.load(open("enrolled.json")).get(name)' '    if key is None:' '        return name, ["not enrolled"]' '    good = hmac.new(key.encode(), body.encode(), hashlib.sha256).digest()' '    if not hmac.compare_digest(good, unb64(sig)):' '        return name, ["bad signature"]' > ~/zt/posture.py

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Write the proxy's device check, part 2

Command
printf '%s\n' '    problems = []' '    if time.time() - report["time"] > MAX_AGE:' '        problems.append("report too old")' '    if report["os"] not in OS_ALLOWED:' '        problems.append("os " + report["os"] + " not allowed")' '    if not report["firewall"]:' '        problems.append("firewall off")' '    if report["updated_days"] > MAX_UPDATE_DAYS:' '        problems.append("not updated for " + str(report["updated_days"]) + " days")' '    return name, problems' >> ~/zt/posture.py

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Enrol the laptop

Command
cd ~/zt && sudo ip netns exec zt-laptop python3 devagent.py enrol laptop && stat -c "%A %U %n" devices/laptop.key enrolled.json

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Turn posture on and ask as amy

Command
cd ~/zt && zt start proxy proxy python3 proxy.py --posture && sudo ip netns exec zt-laptop python3 devagent.py report laptop && zt laptop python3 get.py http://10.30.0.5:8000/grades token=amy.tok posture=laptop.posture

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Write a firewall for the laptop

Command
mkdir -p ~/zt && printf '%s\n' 'table inet laptop' 'delete table inet laptop' 'table inet laptop {' '  chain input {' '    type filter hook input priority 0' '    policy drop' '    iif lo accept' '    ct state established,related accept' '  }' '}' > ~/zt/laptop.nft

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Turn the firewall on and ask again

Command
cd ~/zt && sudo ip netns exec zt-laptop nft -f laptop.nft && sudo ip netns exec zt-laptop python3 devagent.py report laptop && zt laptop python3 get.py http://10.30.0.5:8000/grades token=amy.tok posture=laptop.posture

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Check

Have a go

Check

3 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

Old and copied reports

An attacker may keep an old report from a healthy day. The time inside it gives it away.

A fresh report is different. Copied with a token within two minutes, the proxy cannot tell it from the laptop. See both.

Send a report from ten minutes ago

Command
cd ~/zt && sudo ip netns exec zt-laptop python3 devagent.py report laptop 10 && zt laptop python3 get.py http://10.30.0.5:8000/grades token=amy.tok posture=laptop.posture

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Copy a fresh report to the printer

Command
cd ~/zt && sudo ip netns exec zt-laptop python3 devagent.py report laptop && zt printer python3 get.py http://10.30.0.5:8000/grades token=amy.tok posture=laptop.posture

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

A common mistake

Warning

Many people think a signed device report proves which device sent the request. It proves only that the device signed it once. Bind the report to the connection, with a device certificate in TLS, so a copy is useless elsewhere.

The fix, and how it is seen

The fix is a short report life and a device key that cannot be copied out, such as one in a TPM chip. Add a device certificate on the connection.

Each decision names the device and the address. One device seen from two addresses at once is an alert, and lesson 6 writes it.

Read the device in each decision

Command
cd ~/zt && tail -n 3 logs/proxy.log

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Assignment: decide with the device

Decide like the proxy, with the device.

problems(report, now) lists, in order, "report too old" (more than 120 seconds), "os X not allowed" (not 26.04), "firewall off" and "not updated for N days" (more than 14). access(groups, need, device_problems) returns "allow", or "deny: needs group X" first, or "deny: device: " and the problems joined by ", ".

Code: python
def problems(report, now, max_age=120, os_allowed=("26.04",), max_days=14):
    # report: {"time": ..., "os": ..., "firewall": True, "updated_days": 3}
    # Return a list, in this order, of what is wrong:
    # "report too old" when now - time > max_age, "os X not allowed",
    # "firewall off", "not updated for N days" when updated_days > max_days.
    return []


def access(groups, need, device_problems):
    # "allow" when need is in groups and there are no device problems.
    # Otherwise "deny: needs group X" (the user first) or "deny: device: a, b".
    return "allow"

Make a free account to save your work and track your progress.

Exit quiz

Have a go

Exit quiz

5 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

Teaching a class? Set this module for your students with a teacher guide, marked assignments and a lab for every student.