Sub topic 12
Protecting the Docker Daemon and Socket: Rootless Mode and User Namespaces
This chapter assumes you can build and run containers, you know Linux users and file permissions, and you have read the earlier chapters on isolation primitives, non-root users, and dropped capabilities. Here the focus moves from the container to the service that creates containers: the Docker daemon.
Why the daemon is the most sensitive target
The Docker daemon (dockerd) normally runs as root on the host. It creates namespaces, mounts filesystems, configures networking, and starts every container. Anything that can give the daemon instructions can therefore act as root on the host.
You talk to the daemon through an API. By default the API is a Unix socket at /var/run/docker.sock, owned by root:docker. The docker CLI is only a client for this API.
The consequence is simple. Access to the socket is equivalent to root access to the host. A user who can run docker run can start a container that mounts the host's root filesystem:
docker run --rm -it -v /:/host alpine chroot /host /bin/shThis gives a root shell on the host filesystem. No exploit is involved. The daemon does what it is told.
The attack paths to the daemon
There are three common ways an attacker reaches the daemon.
- A local user in the
dockergroup. Any compromised account in that group can escalate to root, as shown above. - A mounted socket. If a container gets
-v /var/run/docker.sock:/var/run/docker.sock, any process in it can control the host's daemon. A vulnerability in that application then becomes a host takeover. - A network-exposed API. If the daemon listens on TCP, anyone who can reach the port can control it. Port 2375 is plain text with no authentication. Port 2376 is the conventional port for TLS.
Never mount the socket into a container
Tools such as CI runners, dashboards, and reverse proxies often ask for the socket so they can see or start containers. Mounting it as read-only does not help. The :ro flag only stops the socket file from being replaced. A client can still send any API request through it.
Safer alternatives, in order of preference:
- Avoid the need. Use a build tool that does not need the daemon, such as BuildKit run in rootless mode, or a daemonless builder.
- Use a socket proxy. A proxy sits between the container and the socket and allows only specific API calls, for example read-only
GET /containers/json. Treat the proxy as a security-critical component and configure it to deny everything else. - Use a separate daemon. Docker-in-Docker (DinD) runs a second daemon inside a container. It usually needs
--privileged, so it moves the problem instead of removing it. Reserve it for isolated, disposable CI hosts.
Securing remote access
Prefer not to expose the API over TCP at all. If you must manage a remote host, use SSH. The CLI supports it directly, and SSH gives you key-based authentication and encryption without extra daemon configuration:
docker -H ssh://[email protected] psYou can also create a named context so you do not repeat the address:
docker context create prod --docker "host=ssh://[email protected]"
docker --context prod psIf you need a TCP listener, require mutual TLS. The server presents a certificate, and it only accepts clients whose certificates were signed by your certificate authority (CA). This daemon.json fragment shows the settings:
{
"hosts": ["unix:///var/run/docker.sock", "tcp://0.0.0.0:2376"],
"tlsverify": true,
"tlscacert": "/etc/docker/certs/ca.pem",
"tlscert": "/etc/docker/certs/server-cert.pem",
"tlskey": "/etc/docker/certs/server-key.pem"
}A client then connects with its own certificate:
docker --tlsverify \
--tlscacert=ca.pem --tlscert=cert.pem --tlskey=key.pem \
-H tcp://host.example.com:2376 versionTwo common errors apply here. First, if systemd starts Docker with -H fd:// in its unit file, a hosts key in daemon.json conflicts with it and the daemon fails to start. Remove the flag with a systemd drop-in override. Second, tcp://0.0.0.0:2376 listens on every interface. Bind to a specific management address and restrict it with a firewall.
Limiting what the daemon is allowed to be
If the daemon is root, a container escape lands as root. Two features reduce that damage. Both change which host user a container's "root" maps to.
User namespace remapping
Recall from the isolation chapter that a user namespace lets a process have one identity inside the container and a different one outside. With user namespace remapping (userns-remap), the daemon maps container UIDs to a range of unprivileged UIDs on the host. Root inside the container (UID 0) becomes something like UID 165536 on the host.
Enable it in /etc/docker/daemon.json:
{
"userns-remap": "default"
}With default, Docker creates a user and group named dockremap and adds ranges for it in /etc/subuid and /etc/subgid. Restart the daemon and check the result:
sudo systemctl restart docker
grep dockremap /etc/subuid /etc/subgid
docker run -d --name probe alpine sleep 300
ps -o user,pid,cmd -C sleepThe ps output shows the sleep process owned by a high numeric UID on the host, not by root. If an attacker escapes the container, they hold an account with no privileges over host files.
Remapping has costs and gotchas:
- Images are separate. Docker stores images and containers for the remapped range in a different directory, such as
/var/lib/docker/165536.165536. After you enable it, your existing images and containers seem to vanish. They are still in the old directory. - It is daemon-wide. It applies to every container. You can opt a single container out with
--userns=host, but that container then loses the protection, and Docker blocks some combinations such as--privilegedwith remapping unless you opt out. - Bind mounts need matching ownership. A file owned by host UID 1000 is unreadable to a container whose root maps to 165536. You must change ownership or permissions of mounted paths.
- Some features do not combine with it. Sharing the host network or PID namespaces (
--net=host,--pid=host) is not compatible with remapping.
The dockerd process itself is still root. Remapping limits what a container can do after an escape. It does not stop someone who reaches the API.
Rootless mode
Rootless mode runs the daemon and the containers as an ordinary user, with no root privileges at any point. This addresses the API problem as well: someone who takes over the daemon only gains that user's access.
Rootless mode uses a user namespace for the whole daemon. The rootless user gets a range of subordinate UIDs from /etc/subuid and /etc/subgid. Install it as a normal user:
# prerequisites on Debian/Ubuntu: newuidmap, newgidmap, and slirp4netns
sudo apt-get install -y uidmap dbus-user-session slirp4netns
dockerd-rootless-setuptool.sh install
systemctl --user enable --now docker
export DOCKER_HOST=unix://$XDG_RUNTIME_DIR/docker.sock
docker info --format '{{.SecurityOptions}}'The last command should list rootless among the security options. The socket is in the user's runtime directory (/run/user/<uid>/docker.sock), not /var/run.
Rootless mode has limits you should plan for:
| Area | Behavior in rootless mode |
|---|---|
| Ports below 1024 | A normal user cannot bind them. Publish a higher port, or lower `net.ipv4.ip_unprivileged_port_start`. |
| Networking | Uses a user-space network stack (`slirp4netns` or `pasta`), which is slower than the normal bridge. |
| Resource limits | cgroup limits need cgroup v2 with delegation to the user. Without it, `--memory` and `--cpus` may not work. |
| Storage | Uses `overlay2` only on a recent kernel, otherwise falls back to `fuse-overlayfs`. |
| Host files | Bind mounts see only what the user can access. |
| Some features | Features requiring real root, such as certain network drivers, are unavailable. |
Choosing between the two
| Question | `userns-remap` | Rootless mode |
|---|---|---|
| Is `dockerd` root? | Yes | No |
| Does container root map to an unprivileged host UID? | Yes | Yes |
| Protects against API takeover? | No | Mostly. The attacker gets one user, not root. |
| Setup effort | Low, one daemon setting | Higher, per-user install |
| Compatibility cost | Moderate | Higher (networking, ports, cgroups) |
Rootless mode gives the stronger guarantee, and it is a good fit for developer machines and for CI hosts that run untrusted builds. userns-remap suits a shared server where you need a system-wide daemon and can accept its restrictions. You can read the current state with docker info, which shows userns or rootless under Security Options.
Neither option replaces the other controls in this tutorial. Combine them with dropped capabilities, no-new-privileges, and a read-only root filesystem. A useful daemon-wide baseline looks like this:
{
"userns-remap": "default",
"no-new-privileges": true,
"live-restore": true,
"icc": false
}Here no-new-privileges is the default for new containers, live-restore keeps containers running while the daemon restarts for an upgrade, and icc: false stops containers on the default bridge network from talking to each other unless you link them explicitly.
Protect the files and the audit trail
The daemon's own files matter too. Keep these owned by root:root with tight permissions, for example 0644 or stricter for configuration and 0600 for private keys:
/etc/docker/daemon.jsonand/etc/docker/certs/(the TLS keys especially)- The
docker.serviceanddocker.socketunit files /var/run/docker.sock, which should beroot:dockerwith mode0660
Use Linux auditing to record access to these paths. Add rules with auditctl, so changes to the daemon, its configuration, and the Docker data directory appear in the audit log:
sudo auditctl -w /usr/bin/dockerd -k docker
sudo auditctl -w /etc/docker -k docker
sudo auditctl -w /var/run/docker.sock -k docker
sudo auditctl -lRules added this way vanish at reboot. Put them in /etc/audit/rules.d/docker.rules to persist them.
Common errors
- Daemon fails after adding
hosts. A systemd unit already passes-H. Use a drop-in override to clear it. - "Images disappeared" after
userns-remap. Docker switched to the remapped data directory. Disable remapping to see the old images, or pull them again. - Permission denied on a bind mount. The host files are owned by a UID that the remapped or rootless container cannot access. Adjust ownership to the mapped UID.
- Rootless
--memoryis ignored. cgroup v2 is not delegated to the user. Checkdocker infofor warnings. - Rootless daemon stops at logout. Enable lingering with
sudo loginctl enable-linger <user>.
Exercise
A CI job needs to start sibling containers, so a teammate proposes mounting /var/run/docker.sock read-only (:ro) into the job container. Explain why this does not make the setup safe, and name two better options.
Show answer
The :ro flag only prevents the socket file from being modified or replaced. It does not restrict the API requests sent through the socket, so the job can still start a privileged container that mounts the host's root filesystem and gain root on the host. Better options are to use a daemonless or rootless builder so no socket is needed, to place a socket proxy that allows only specific read-only API calls between the job and the daemon, or to run the job against a separate, disposable daemon on an isolated host.
Exercise
You enable "userns-remap": "default" and restart Docker. docker images is now empty, and a container with a bind mount of /srv/data (owned by host UID 1000) cannot write to it. Explain both symptoms and how to fix the second.
Show answer
With remapping enabled, Docker uses a separate storage directory for the remapped UID range (for example /var/lib/docker/165536.165536), so images and containers created earlier are not visible until you pull them again or disable remapping. The bind mount fails because container root now maps to an unprivileged host UID such as 165536, which has no write permission on files owned by UID 1000. Fix it by changing the ownership or permissions of /srv/data so the mapped UID can write, for example sudo chown 165536:165536 /srv/data, or by using a named volume that Docker creates with the right ownership.