Courses3 levels
Level 1 · Foundations11 courses
Level 2 · Core5 courses
Level 3 · Advanced5 courses
Labs8 topics
Library Practice exams AI Range Pricing Start free

Lesson 05 · 40 minutes

Isolate the model service and audit the isolation settings

After this lesson you can
  • Limit what the service can read, write and use with file modes and ulimit
  • Audit the settings of a running process with a script that reports each failure
  • Run a program in a sandbox with no network and a read-only file system
Lab files of this lesson (22)

The lab folder as it stands after this lesson. Unzip it in ~/krlab.

More

The zip holds every file that the course has printed up to here. To start this lesson with the files of the earlier lessons only, take the zip of the lesson before. Type the code yourself first: you learn more.

Scenario

A security review asks one question about the model service: "If someone finds a bug in it and takes control of the process, what can that process do?" Today the answer is: everything that you can do. It can change the model file, read the keys of every client, fill the disk, and call any server on the network. You cannot make a bug impossible. You can make it small: a process that has few rights has little to lose, and little to give away.

Recall

Lesson 4: which file mode do secret files get, and how does the scanner treat a file with another mode?

Mode 600: read and write for the owner, nothing for anyone else. The scanner reports a secret file that has any group or other bit set.

Lesson 2: what does the service check before it loads the model?

The hash of model.json must equal the hash in manifest.json, and the file must have the right shape. A changed model file is refused. It does not stop a person who can change both files, and this lesson makes both files read-only.

The idea

Least privilege means that a process gets only the rights that its job needs. Four layers cost almost nothing on Linux. The table lists them from the inside out, and the drawing shows them from the outside in.

LayerSettingWhat it limits
UserA user without administrator rights (a separate system user, if you can make one)What the process may do to the system
FilesModel files read-only. A work folder that only the owner can enter. Secrets of mode 600What it can change and read
Limitsulimit: open files, memory, file sizeHow much damage a runaway or hostile process can do
Sandboxbwrap (bubblewrap) or unshareWhat it can see: no network, a read-only file system

A platform has equivalents: a container that runs as a non-root user with a read-only root file system, and limits for memory and processes set by the platform. This course cannot test those. The ideas are the same.

Layers of isolation, from the outside in
Sandboxno network, read-only file systemLimitsopen files, memory, file sizeFilesmodel read-only, work folder privateUsernot root, no sudo rightsSandboxno network, read-only file systemLimitsopen files, memory, file sizeFilesmodel read-only, work folder privateUsernot root, no sudo rights

Worked example

1. Make the files safe

chmod 444 gives every user read and nothing else. chmod 700 lets only the owner enter a folder. The model files are created by the pipeline and only read by the service, so they are read-only. Note the honest limit: you own these files, so you can change the mode back. The protection is full when the files belong to another user (step 6).

A mode has three groups of letters, for the owner, the group and everyone else. r is read, w is write, x is run (or enter, for a folder), and - means that the right is missing. So rwx------ gives the owner everything and nobody else anything.

The mode of model.json after chmod 444
-a file (d is a folder)r--owner: readr--group: readr--others: read-a file (d is a folder)r--owner: readr--group: readr--others: read
chmod 444 models/current/model.json models/current/manifest.json
mkdir -p work
chmod 700 work
ls -l models/current
ls -ld work
total 8
-r--r--r-- 1 you you  96 Nov 21 13:36 manifest.json
-r--r--r-- 1 you you 190 Nov 21 13:36 model.json
drwx------ 2 you you 40 Nov 21 13:42 work

2. Start the service with limits

ulimit sets a limit for the shell and for every program that it starts. -n is the number of open files, -v the memory of the process in kilobytes, and -f the biggest file that it may write, in blocks of 1024 bytes. A pair of parentheses runs the commands in a subshell, so the limits do not stay in your own shell. exec replaces the subshell with the program, so the process number stays the same. umask 077 makes every file that the service creates private.

export KR_GATEWAY_TOKEN=$(cat secrets/gateway.token)
( ulimit -n 64 -v 2097152 -f 10240; umask 077; exec python service.py 8421 2> service.log > /dev/null ) &
echo $! > service.pid
sleep 1

3. Save the audit script

audit_isolation.py reads the settings of a running process from /proc/PID/status and /proc/PID/limits (Linux files that the kernel keeps for each process), and the modes of the files. audit turns the settings into seven lines, one for each rule. It is a pure function, so you can also give it settings that are written in a file: a team can then audit a plan before it builds it.

audit_isolation.py

"""audit_isolation.py: check the isolation settings of a running service and report each failure.

    python3 audit_isolation.py PID MODEL_FILE WORK_DIR SECRETS_DIR      read the settings of a process, Linux only
    python3 audit_isolation.py --settings settings.json                 audit settings that are written down (modes in octal text)
"""
import json
import os
import re
import stat
import sys
from pathlib import Path


def proc_limits(pid):
    """Read /proc/PID/limits: the soft limit of each resource, None for 'unlimited'."""
    limits = {}
    for line in Path(f"/proc/{pid}/limits").read_text().splitlines()[1:]:
        name, soft = re.split(r"\s{2,}", line.strip())[:2]
        limits[name] = None if soft == "unlimited" else int(soft)
    return limits


def gather(pid, model_file, work_dir, secrets_dir):
    """Collect the settings of a process and its files into one dict."""
    uid = int(re.search(r"Uid:\s+(\d+)", Path(f"/proc/{pid}/status").read_text()).group(1))
    mode = lambda p: stat.S_IMODE(os.stat(p).st_mode)
    limits = proc_limits(pid)
    return {"uid": uid, "model_mode": mode(model_file), "work_mode": mode(work_dir),
            "secret_modes": [mode(p) for p in Path(secrets_dir).glob("*")],
            "nofile": limits["Max open files"], "memory": limits["Max address space"], "fsize": limits["Max file size"]}


def audit(s):
    """Return (name, ok, detail) for each rule. Pure function: the same settings give the same lines."""
    limited = lambda v, top: v is not None and v <= top
    return [("not root", s["uid"] != 0, f"uid {s['uid']}"),
            ("model read-only", not s["model_mode"] & 0o222, f"mode {s['model_mode']:o}"),
            ("work private", not s["work_mode"] & 0o077, f"mode {s['work_mode']:o}"),
            ("secrets private", all(not m & 0o077 for m in s["secret_modes"]), f"modes {[format(m, 'o') for m in s['secret_modes']]}"),
            ("open files limited", limited(s["nofile"], 256), f"limit {s['nofile']}"),
            ("memory limited", limited(s["memory"], 4 * 2**30), f"limit {s['memory']}"),
            ("file size limited", limited(s["fsize"], 10 * 2**20), f"limit {s['fsize']}")]


def read_settings(path):
    """Read settings that are written down in a file. A mode is a text in octal: "644"."""
    with open(path) as f:
        settings = json.load(f)
    for name in ("model_mode", "work_mode"):
        settings[name] = int(settings[name], 8)
    settings["secret_modes"] = [int(m, 8) for m in settings["secret_modes"]]
    return settings


if __name__ == "__main__":
    settings = read_settings(sys.argv[2]) if sys.argv[1] == "--settings" else gather(sys.argv[1], *sys.argv[2:5])
    results = audit(settings)
    for name, ok, detail in results:
        print(("ok   " if ok else "FAIL ") + name.ljust(20) + detail)
    print(f"isolation ok: {sum(ok for _, ok, _ in results)} of {len(results)}")
    sys.exit(0 if all(ok for _, ok, _ in results) else 1)

4. Audit the running service

The arguments are the process number, the model file, the work folder and the folder of secrets. $$ is the process number of your own shell.

python audit_isolation.py $(cat service.pid) models/current/model.json work secrets
python audit_isolation.py $$ models/current/model.json work secrets
ok   not root            uid 1000
ok   model read-only     mode 444
ok   work private        mode 700
ok   secrets private     modes ['600', '600', '600']
ok   open files limited  limit 64
ok   memory limited      limit 2147483648
ok   file size limited   limit 10485760
isolation ok: 7 of 7
ok   not root            uid 1000
ok   model read-only     mode 444
ok   work private        mode 700
ok   secrets private     modes ['600', '600', '600']
FAIL open files limited  limit 1048576
FAIL memory limited      limit None
FAIL file size limited   limit None
isolation ok: 4 of 7

Your limit values for the shell can differ: the soft limit of open files is often 1024. The service passes all seven rules. Your shell passes the four rules about files and user, and fails the three rules about limits: it has none. The audit says what is wrong, and it ends with exit code 1, so a build can use it.

5. Try the sandbox (optional)

bwrap (bubblewrap) starts a program in a new set of namespaces: private views of the file system, the network and other things. If command -v bwrap prints nothing, skip this step. The flags below were tested on one Linux system, and other systems can need other flags or refuse to run it. --ro-bind / / shows the whole file system read-only, --bind makes one folder writable, and --unshare-all gives the program its own empty network.

probe.py tries four things that a hostile process might try.

What the probe may do in the sandbox
SandboxYour computerProbeWork folderModel fileTmp folderModel service1234SandboxYour computerProbeWork folderModel fileTmp folderModel service1234
  1. Probe → Work folder: write work/out.txt: allowed
  2. Probe → Model file (blocked): write, mode 444 (also outside)
  3. Probe → Tmp folder (blocked): write /tmp/probe.txt
  4. Probe → Model service (blocked): connect to port 8421

probe.py

"""probe.py: try what a compromised service might try, and print what works."""
import socket


def can_write(path):
    try:
        open(path, "a").close()
        return "yes"
    except OSError:
        return "no"


for path in ["models/current/model.json", "work/out.txt", "/tmp/probe.txt"]:
    print("write", path.ljust(26), can_write(path))
try:
    socket.create_connection(("127.0.0.1", 8421), timeout=1).close()
    print("connect 127.0.0.1:8421".ljust(32), "yes")
except OSError:
    print("connect 127.0.0.1:8421".ljust(32), "no")
python probe.py
bwrap --ro-bind / / --dev /dev --proc /proc --bind "$PWD/work" "$PWD/work" --unshare-all --die-with-parent python probe.py
rm -f work/out.txt /tmp/probe.txt
write models/current/model.json  no
write work/out.txt               yes
write /tmp/probe.txt             yes
connect 127.0.0.1:8421           yes
write models/current/model.json  no
write work/out.txt               yes
write /tmp/probe.txt             no
connect 127.0.0.1:8421           no

Outside the sandbox the probe writes in work and in /tmp, and it reaches the service. Inside, it writes only in work, and it has no network. The model file is read-only in both cases, because of the mode.

unshare is simpler and also gives a private network. It needs --map-root-user when you are not an administrator, and that has a side effect that you must know about. A system that restricts unprivileged user namespaces (Ubuntu 24.04 does by default) refuses this command, and it can refuse the bwrap step for the same reason. Skip the step that is refused.

unshare --net --map-root-user python probe.py
rm -f work/out.txt /tmp/probe.txt
write models/current/model.json  yes
write work/out.txt               yes
write /tmp/probe.txt             yes
connect 127.0.0.1:8421           no

Inside that namespace you are root (mapped to your own user), and root may write a file that has mode 444. The network is gone, but the model file is writable again. So use unshare for the network only, and do not count it as a file protection.

Stop the service that step 2 started, so that port 8421 is free for step 6 and for the next lessons.

kill $(cat service.pid)

6. A separate user (needs administrator rights)

This step needs sudo, and the course could not test it. It runs the service as a new system user that has no home folder and no login shell. That user cannot enter your home folder, so the commands copy service.py and the models to /srv/krmodel, and the service uses the system python3 (it needs only the standard library). The token goes in through the environment of sudo, not on a command line, because ps shows every command line.

sudo useradd --system --no-create-home --shell /usr/sbin/nologin krmodel
sudo install -d -m 755 /srv/krmodel
sudo cp -r service.py models /srv/krmodel/
sudo chown -R root:krmodel /srv/krmodel/models
sudo chmod -R u=rwX,g=rX,o= /srv/krmodel/models
sudo install -d -o krmodel -m 700 /srv/krmodel/work
KR_GATEWAY_TOKEN=$(cat secrets/gateway.token) sudo --preserve-env=KR_GATEWAY_TOKEN -u krmodel sh -c 'cd /srv/krmodel && exec python3 service.py 8421'

Now the model files belong to root. The service can read them through the group, and it cannot change them. In a container, the same idea is a USER instruction and a read-only root file system. In production a service unit gives the token with LoadCredential=.

Stop the service with Ctrl+C. It runs in the foreground here. Then remove the user and the folder, which are yours to clean up. rm -rf deletes without asking, so check that the path is exactly /srv/krmodel.

sudo userdel krmodel
sudo rm -rf /srv/krmodel

Your turn

A team wrote down the isolation settings of their planned service in settings-bad.json. Save it. Modes are texts in octal, and null means that no limit is set.

settings-bad.json

{"uid": 0, "model_mode": "644", "work_mode": "755", "secret_modes": ["600", "640"],
 "nofile": null, "memory": 8589934592, "fsize": 1048576}

Audit it with python audit_isolation.py --settings settings-bad.json. Then write settings-fixed.json, with the same keys, so that the audit prints isolation ok: 7 of 7. Give each value the setting that the running service had in step 4 (the modes of the model file, the work folder and the secrets, and the three limits), so that the service can still read its model.

Check yourself

The model file has mode 444 and you own it. Why is that not full protection?

As the owner you can run chmod and change it back, and so can any code that runs as you, including a hijacked service. The mode stops accidents and code that merely opens the file for writing. For full protection the file belongs to another user and the service does not run as its owner, or the file system is mounted read-only for the service.

Why limit memory and open files for a service that works well today?

A limit turns a runaway or an attack into a failure of one process, which a supervisor restarts. Without it, one request that makes the process eat all memory or all file handles can bring down the whole computer, including the other services on it.

The sandbox blocks the network. What must you allow when the service really needs a database?

Only that connection, and nothing else: a container platform does this with a network policy (a list of allowed destinations), and a firewall can do it on one computer. A sandbox with the whole network open is no longer a sandbox for network risks.

Field notes

  • A container is not a security boundary by itself. It shares the kernel of its host. Run it as a non-root user, drop capabilities, mount the root file system read-only, and add a profile such as seccomp, which limits the system calls that a process may make. This course cannot test any of these.
  • Put the limits in the unit that starts the service (a systemd service has settings such as LimitNOFILE, MemoryMax, NoNewPrivileges and ProtectSystem), so that nobody has to remember a command line. Part 2 of the Linux course teaches units.
  • Audit a running process, not only a plan. /proc/PID/limits shows what the kernel enforces, and it is the truth that a configuration file only hopes for.
  • A model file that must be a pickle (some libraries give you no choice) should be loaded in a sandbox like the one in step 5, with no network, and only after its hash matches a trusted record (lesson 6).
  • Keep the work folder small and temporary. A service that needs to write only a log and a scratch file needs no other write access.