Linux Containers by Hand. Part 7: Restricting root privileges in a container

All parts of the series “Linux Containers by Hand”

In Part 3, our container built with shell commands kept every root capability. One mount command made its read-only root writable again. In Part 4, the nginx workers with UID 101 appeared as syslog on the host because the container and host shared user IDs. Today we will look at three mechanisms that address this: capabilities, seccomp system call filters, and the user namespace. At the end we will run runc as an ordinary user.

The AppArmor profile, example seccomp filter, and rootless script are in the linux-containers-by-hand repository.


Lab setup

Item Value
Machine lincont-lab.example.com, Hyper-V VM
OS Ubuntu Server 26.04.1, kernel 7.0.0
containerd, runc, nerdctl 2.4.2, 1.5.2 (libseccomp 2.6.1), 2.4.2
Ordinary user lab, UID 1000
Image docker.io/library/alpine:3.24

Run the commands as root (sudo -i), except in the rootless section. Use make-bundle.sh from Part 2 to build an runc bundle from the image.


Capabilities

Root privileges are split into capabilities

Traditional Unix used a simple check: UID 0 could do everything and everyone else was limited to what they owned or could access. Linux divides root privileges into capabilities. The kernel checks capabilities for most privileged operations. Each process has five sets.

  • CapPrm (permitted) is the set the process may use.
  • CapEff (effective) is the active set consulted by privilege checks.
  • CapBnd (bounding) sets the ceiling for capabilities a program can acquire from a file at exec time.
  • CapInh and CapAmb (inheritable and ambient) are involved in passing capabilities to programs the process runs.
grep Cap /proc/self/status
capsh --decode=000001ffffffffff | tr ',' '\n' | wc -l
capsh --decode=0000000020000420
capsh --decode=00000000a80425fb
CapInh:	0000000000000000
CapPrm:	000001ffffffffff
CapEff:	000001ffffffffff
CapBnd:	000001ffffffffff
CapAmb:	0000000000000000
41
0x0000000020000420=cap_kill,cap_net_bind_service,cap_audit_write
0x00000000a80425fb=cap_chown,cap_dac_override,cap_fowner,cap_fsetid,cap_kill,cap_setgid,cap_setuid,cap_setpcap,cap_net_bind_service,cap_net_raw,cap_sys_chroot,cap_mknod,cap_audit_write,cap_setfcap

Host root has all 41 capabilities. capsh decodes the bitmask. 20000420 is the set of three that runc kept in Part 2. a80425fb is the set of fourteen nerdctl gives a container, the same default set as Docker. We will see it below.

Drop individual capabilities

capsh --drop removes capabilities from the bounding set and launches a shell without them. Try three.

echo secret > /tmp/c7-secret
chmod 000 /tmp/c7-secret
ls -l /tmp/c7-secret
cat /tmp/c7-secret
capsh --drop=cap_dac_override,cap_dac_read_search -- -c 'grep CapEff /proc/self/status; cat /tmp/c7-secret'
python3 -c 'import socket; socket.socket().bind(("", 80)); print("bound to 80")'
capsh --drop=cap_net_bind_service -- -c "python3 -c 'import socket; socket.socket().bind((\"\", 80)); print(\"bound to 80\")' 2>&1 | tail -1"
capsh --drop=cap_sys_admin -- -c 'mount -t tmpfs demo /mnt'
rm /tmp/c7-secret
---------- 1 root root 7 Nov 10 20:35 /tmp/c7-secret
secret
CapEff:	000001fffffffff9
cat: /tmp/c7-secret: Permission denied
bound to 80
PermissionError: [Errno 13] Permission denied
mount: /mnt: permission denied.
       dmesg(1) may have more information after failed mount system call.
  • Root can read a file with mode 000 because CAP_DAC_OVERRIDE bypasses file permission checks. Without that capability and CAP_DAC_READ_SEARCH, the normal permission check applies even to root.
  • CAP_NET_BIND_SERVICE allows binding a port below 1024.
  • Mounting requires CAP_SYS_ADMIN. It also allows changing hostnames, creating namespaces, and many other privileged operations, which is why it is sometimes called “the new root.” The container is given no such capability here.

Set capabilities in runc

The runc spec template keeps the three capabilities we saw in Part 2. Leave the root writable this time and try changing file ownership, mounting tmpfs, and changing the hostname.

./make-bundle.sh docker.io/library/alpine:3.24 /srv/c7 > /dev/null
cd /srv/c7
jq '.root.readonly = false | .process.args = ["sh", "-c", "grep CapEff /proc/self/status; touch /c7; chown 1000 /c7; ls -ln /c7; mount -t tmpfs t /mnt; hostname other"]' config.json > c.json && mv c.json config.json
runc run demo
jq '.process.capabilities[] += ["CAP_CHOWN"]' config.json > c.json && mv c.json config.json
runc run demo
rm rootfs/c7
CapEff:	0000000020000420
chown: /c7: Operation not permitted
-rw-r--r--    1 0        0                0 Nov 10 20:35 /c7
mount: permission denied (are you root?)
hostname: sethostname: Operation not permitted
CapEff:	0000000020000421
-rw-r--r--    1 1000     0                0 Nov 10 20:35 /c7
mount: permission denied (are you root?)
hostname: sethostname: Operation not permitted

The process runs as root but still needs CAP_CHOWN to change file ownership. After adding it to config.json, chown worked. Mounting and changing the hostname still failed. Give the application only what it needs, as we did for nginx with CAP_SETUID and CAP_SETGID in Part 4.

The template also sets noNewPrivileges: true. A setuid executable normally runs with its owner’s privileges, which is how a root-owned passwd lets an ordinary user change a password. With this flag, the kernel prevents the process and its descendants from gaining privileges through such executables.


seccomp

Filter system calls

Capabilities determine what a process can do. Every system call still exposes kernel code, and a flaw in a rarely used call could let a process escape. seccomp (secure computing) lets a process install a small BPF program that the kernel runs at every system call. It inspects the call number and arguments and can allow it, return an error, kill the process, or log it. Descendants inherit the filter, and it cannot be removed.

Compare the host with a nerdctl container.

grep -E '^(NoNewPrivs|Seccomp)' /proc/self/status
nerdctl run --rm docker.io/library/alpine:3.24 sh -c 'grep -E "^(CapEff|NoNewPrivs|Seccomp)" /proc/self/status; unshare -U true; echo "unshare exit $?"'
nerdctl run --rm --security-opt seccomp=unconfined docker.io/library/alpine:3.24 sh -c 'grep -E "^Seccomp:" /proc/self/status; unshare -U true; echo "unshare exit $?"'
NoNewPrivs:	0
Seccomp:	0
Seccomp_filters:	0
CapEff:	00000000a80425fb
NoNewPrivs:	0
Seccomp:	2
Seccomp_filters:	1
unshare: unshare(0x10000000): Operation not permitted
unshare exit 1
Seccomp:	0
unshare exit 0

The host has no filter (Seccomp: 0). In the nerdctl container, mode 2 means filtering is active. unshare() with CLONE_NEWUSER (0x10000000) is rejected. The default profile shared with Docker allows namespace creation only with CAP_SYS_ADMIN, because a new user namespace exposes a substantial amount of kernel code. seccomp=unconfined disables the filter and the call succeeds.

Write a filter for runc

runc builds the filter from linux.seccomp in config.json. Write one that allows other calls, returns EPERM (1) when a process creates a directory, and kills the process if it changes a file’s permissions.

cat > seccomp.json <<'EOF'
{
    "defaultAction": "SCMP_ACT_ALLOW",
    "architectures": [
        "SCMP_ARCH_X86_64"
    ],
    "syscalls": [
        {
            "names": [
                "mkdir",
                "mkdirat"
            ],
            "action": "SCMP_ACT_ERRNO",
            "errnoRet": 1
        },
        {
            "names": [
                "chmod",
                "fchmod",
                "fchmodat",
                "fchmodat2"
            ],
            "action": "SCMP_ACT_KILL_PROCESS"
        }
    ]
}
EOF
jq --slurpfile s seccomp.json '.linux.seccomp = $s[0] | .process.args = ["sh", "-c", "grep -E \"^Seccomp\" /proc/self/status; mkdir /dev/shm/x; echo \"mkdir exit $?\"; touch /dev/shm/f; chmod 600 /dev/shm/f; echo \"chmod exit $?\""]' config.json > c.json && mv c.json config.json
runc run demo
echo "exit $?"
Seccomp:	2
Seccomp_filters:	1
mkdir: can't create directory '/dev/shm/x': Operation not permitted
mkdir exit 1
Bad system call (core dumped)
chmod exit 159
exit 0
  • architectures selects the CPU architectures the rules apply to. System call numbers differ across architectures. One operation can also have several variants, so the rules list both older and newer calls.
  • mkdir got “Operation not permitted,” just as it would after a privilege failure. The program can decide how to handle the error.
  • chmod died with SIGSYS (“Bad system call”), yielding 159 = 128 + 31. Alpine runs chmod as a separate process, so the shell continued and printed its exit status.

SCMP_ACT_ERRNO lets programs handle a failure. SCMP_ACT_KILL_PROCESS ensures that the offending process stops.


User namespaces

Map user and group IDs

A user namespace isolates user and group IDs. A mapping can say that UIDs 0 through 65535 inside correspond to 100000 through 165535 outside. A process can be root with all capabilities inside, but those capabilities apply only to resources governed by that namespace, such as the namespaces it owns. To the host, it is ordinary user 100000.

Try creating a user namespace as an ordinary user.

unshare --user --map-root-user id
unshare: write failed /proc/self/uid_map: Operation not permitted

It fails because Ubuntu, starting with 24.04 and including our 26.04 lab, allows ordinary users to create user namespaces only through programs whose AppArmor profile permits it. The kernel setting kernel.apparmor_restrict_unprivileged_userns is 1 in the lab. We return to this in the last section. For now, create the namespace as root, which can write its own mapping.

mkdir -p /srv/c7u
chown 100000:100000 /srv/c7u
unshare --user --map-users=0:100000:65536 --map-groups=0:100000:65536 --setuid 0 --setgid 0 --uts --mount --pid --fork --mount-proc sh -c 'id; cat /proc/self/uid_map; grep CapEff /proc/self/status; hostname box && hostname; touch /srv/c7u/file; ls -ln /srv/c7u /etc/shadow; head -c 20 /etc/shadow; touch /etc/c7test'
ls -ln /srv/c7u
uid=0(root) gid=0(root) groups=0(root)
         0     100000      65536
CapEff:	000001ffffffffff
box
-rw-r----- 1 65534 65534 843 Nov 10 12:18 /etc/shadow

/srv/c7u:
total 0
-rw-r--r-- 1 0 0 0 Nov 10 20:35 file
head: cannot open '/etc/shadow' for reading: Permission denied
touch: setting times of '/etc/c7test': Permission denied
total 0
-rw-r--r-- 1 100000 100000 0 Nov 10 20:35 file
  • --map-users=0:100000:65536 maps 65,536 IDs starting at 0 inside to IDs starting at 100000 outside. See /proc/self/uid_map. --setuid 0 makes the process root inside. Without it, the process would keep its host UID 0, which is outside the mapping.
  • The process has all 41 capabilities inside. It can change the hostname because the uts namespace was created in, and is owned by, its user namespace.
  • The file it creates belongs to UID 0 inside and 100000 on the host. It could write only to the directory we had already given to UID 100000.
  • The host’s /etc/shadow belongs to host root, which has no mapping, so the process sees 65534 (nobody). Container root cannot read it or write under /etc because the host sees an ordinary user.

Recall nginx from Part 4. Run a process as UID 101 in this namespace and inspect it from the host.

unshare --user --map-users=0:100000:65536 --map-groups=0:100000:65536 --setuid 0 --setgid 0 --pid --fork --mount --mount-proc setpriv --reuid=101 --regid=101 --clear-groups sleep 30 &
sleep 1
ps -o user,uid,pid,cmd -C sleep
kill %1
rm -rf /srv/c7u
USER       UID     PID CMD
100101   100101   5064 sleep 30

It is UID 101 inside and 100101 on the host, an ID that owns nothing there and no longer overlaps syslog. Ranges for these mappings are assigned in /etc/subuid and /etc/subgid. The lab gives lab the range 100000:65536. newuidmap from the uidmap package lets the user write mappings for those IDs without running as root.


Run a rootless container

runc can run as an ordinary user. In this rootless setup, container root maps to that user, so escaping the container would give a process only that user’s privileges. First, allow it through AppArmor. Ubuntu ships /etc/apparmor.d/runc for the packaged binary at /usr/bin/runc or /usr/sbin/runc. Our binary is in /usr/local/sbin. Copy the profile and use our path.

sed 's|^profile runc /usr/{bin,sbin}/runc|profile runc-local /usr/local/sbin/runc|; s|<local/runc>|<local/runc-local>|' /etc/apparmor.d/runc > /etc/apparmor.d/runc-local
grep -v '^#' /etc/apparmor.d/runc-local | grep .
apparmor_parser -r /etc/apparmor.d/runc-local
aa-status | grep runc
mkdir -p /srv/c7r
cp -a /srv/c7/rootfs /srv/c7r/rootfs
abi <abi/5.0>,
include <tunables/global>
profile runc-local /usr/local/sbin/runc flags=(unconfined) {
  userns,
  @{exec_path} mr,
  # Site-specific additions and overrides. See local/README for details.
  include if exists <local/runc-local>
}
   runc
   runc-local

The profile is unconfined and adds the userns permission to create user namespaces. We copied the container root into a separate directory. It is owned by root, and the container only needs read access.

For the remaining commands, log in over SSH as lab. runc spec --rootless creates the template.

id -u; echo $XDG_RUNTIME_DIR
mkdir -p ~/c7r
cd ~/c7r
runc spec --rootless
jq -c '.linux.uidMappings, .linux.gidMappings, [.linux.namespaces[].type]' config.json
jq -c '.mounts[] | select(.destination == "/sys")' config.json
1000
/run/user/1000
[{"containerID":0,"hostID":1000,"size":1}]
[{"containerID":0,"hostID":1000,"size":1}]
["pid","ipc","uts","mount","cgroup","user"]
{"destination":"/sys","type":"none","source":"/sys","options":["rbind","nosuid","noexec","nodev","ro"]}
  • The mapping has one line: UID 0 inside is UID 1000 on the host. An ordinary user needs newuidmap to add more IDs.
  • There are six namespaces. user is included, and network is absent, so the container shares the host’s network. An ordinary user cannot create veth pairs and attach them to a host bridge. Rootless runtimes use programs such as slirp4netns or pasta to carry traffic through ordinary sockets.
  • /sys is bind-mounted from the host. A new sysfs mount requires control of the network namespace.

Start the container.

jq '.root.path = "/srv/c7r/rootfs" | .process.terminal = false | .process.args = ["sh", "-c", "id; cat /proc/self/uid_map; grep CapEff /proc/self/status; hostname; ls -ln /etc/shadow; touch /dev/shm/x && ls -ln /dev/shm"]' config.json > c.json && mv c.json config.json
runc run demo
echo "exit $?"
uid=0(root) gid=0(root) groups=65534(nobody),65534(nobody),65534(nobody),65534(nobody),65534(nobody),65534(nobody),65534(nobody),0(root)
         0       1000          1
CapEff:	0000000020000420
runc
-rw-r-----    1 65534    65534          260 Nov  5 09:19 /etc/shadow
total 0
-rw-r--r--    1 0        0                0 Nov 10 20:36 x
exit 0

Inside we are root with the same three capabilities and hostname runc. The host’s supplementary groups for lab are unmapped and appear as nobody. The image’s /etc/shadow belongs to host root, which is also unmapped. Inspect the running container from the host.

jq '.process.args = ["sleep", "100"]' config.json > c.json && mv c.json config.json
runc run -d demo > /dev/null 2>&1
runc list
ps -o user,pid,cmd -C sleep
ls $XDG_RUNTIME_DIR/runc
runc kill demo KILL; sleep 1; runc delete demo
cd ~
rm -rf ~/c7r
ID          PID         STATUS      BUNDLE           CREATED                         OWNER
demo        5133        running     /home/lab/c7r    2026-11-10T20:36:19.64593127Z   lab
USER         PID CMD
lab         5133 sleep 100
demo

lab owns the container process. runc stores state under $XDG_RUNTIME_DIR/runc because the user cannot write to /run/runc. A rootless container can receive cgroup limits if systemd has delegated a subtree to the user, like the subtree delegated to the containerd service in Part 5.


What each mechanism controls

Mechanism What it controls In config.json
Capabilities Which privileged operations root can perform process.capabilities
no_new_privs Privilege gains through setuid executables process.noNewPrivileges
seccomp Which system calls are available linux.seccomp
user namespace What host identity container root has linux.namespaces, linux.uidMappings, linux.gidMappings

Each layer constrains the process in a different way. Root needs the appropriate capability to mount. Even with it, the process needs access to the system call. If the process escapes, the user namespace still maps it to an ordinary host user.


Clean up

Run these commands as root.

apparmor_parser -R /etc/apparmor.d/runc-local
rm /etc/apparmor.d/runc-local
rm -rf /srv/c7 /srv/c7r
rmdir /sys/fs/cgroup/lab
nerdctl rmi docker.io/library/alpine:3.24 > /dev/null

You can keep the profile if you plan to continue running runc rootless. It permits /usr/local/sbin/runc to create user namespaces.


Use the repository examples

The 07-security directory contains the following files.

  • runc-local.apparmor is the profile for runc at /usr/local/sbin.
  • seccomp.json is this part’s filter, which goes in linux.seccomp.
  • rootless.sh runs an runc container as an ordinary user with a given root. It creates the bundle in a temporary directory and removes it on exit.
./rootless.sh /srv/c7r/rootfs sh -c 'id -u; cat /proc/self/uid_map'
0
         0       1000          1

References


Next, in the final part, we will write a small C runtime that creates namespaces with clone(), switches roots, applies cgroup limits, and drops capabilities, bringing together the steps we have worked through in this series.

Only registered users can leave a comment.

Sign in or register to leave a comment.