One Zero-Day Away From Root: Locking Down Traefik's Docker Socket (Without Breaking Production)

Part 2 of a series on hardening a small production stack without an audit budget. ← Part 1

If you run Traefik on Docker, this line is probably in your configuration:

volumes:
  - /var/run/docker.sock:/var/run/docker.sock:ro

Nearly every tutorial has it. It’s how Traefik finds your services. It also hands the one process that faces the internet full control of Docker. One remote-code-execution bug in Traefik, and an attacker owns the host: every container, every database, every secret. Internet-facing proxies are exactly where attackers hunt for zero-days, because one bug reaches every company running them.

Mine had that line, on a Traefik release years out of date with 87 known high and critical vulnerabilities. Here’s how I moved it to v3, took the socket away, and ran it as a non-root user, with under two minutes of downtime. Plus three things my checks missed, one of which reached production.


Why :ro doesn’t help

The socket is the Docker API. Anything that can reach it can start a container with the host’s root filesystem mounted, run it privileged, and read or change every other container. That’s root on the host in one API call.

:ro makes the socket file read-only, not the API behind it. A read-only mount can still send POST /containers/create.

“Traefik only reads from it” is true until someone exploits Traefik.

The goal: even fully compromised, Traefik can see routing metadata and nothing else.


The target architecture

                 internet
                    │  :80 / :443 (host mode)
                    ▼
        ┌─────────────────────────┐
        │ Traefik v3              │  runs as uid 65532 (non-root)
        │ listens :8000 / :8443   │  no Docker socket mounted
        └───────────┬─────────────┘
      public net    │   socket_proxy net (internal, no internet)
   (to your apps)   │
                    ▼
        ┌─────────────────────────┐
        │ docker-socket-proxy     │  allows GET services/tasks/networks/nodes
        │ (not internet-facing)   │  everything else → 403
        └───────────┬─────────────┘
                    │ /var/run/docker.sock
                    ▼
                Docker API

Three changes:

  1. Traefik v3. Known HIGH/CRITICAL vulnerabilities in the image went from 87 to 2, and both are one CVE listed for two OS packages, in a library Traefik doesn’t use.
  2. A socket proxy. A tiny HAProxy-based service that exposes an allowlist of Docker API endpoints. It lives on a private network with no internet access, and only Traefik can reach it.
  3. Non-root Traefik. An attacker with code execution lands as an unprivileged user in a container with nothing sensitive mounted except its own certificates.

The socket proxy still holds the socket, so it’s privileged. But it isn’t internet-facing, its attack surface is tiny, and the only thing that can talk to it is Traefik, which now only has read permission.


The method: rehearse, diff, then cut over

The configuration change is small. The risk is in what you don’t notice: a route that silently changes, a redirect that picks up the wrong port, a certificate that can’t be written. So the process matters more than the YAML:

  1. Inventory and back up the current config, labels, and certificate storage.
  2. Snapshot external behavior of every public hostname: status codes, redirects, certificate fingerprints, security headers, TLS behavior.
  3. Rehearse the new setup in throwaway containers that read your live configuration but serve no traffic.
  4. Diff the rendered configuration, not the source file.
  5. Cut over, then re-snapshot and diff. The goal is an identical result.

I shipped it as two deploys on the same day: v3 first with the same socket access, then the socket proxy and non-root change once v3 passed the edge diff. If something broke, I’d know which change did it.

Snapshot external behavior

This loop, run from outside your network, captures how every hostname behaves. Run it before and after, then diff the two files. Any line that changes is something to investigate.

#!/bin/bash
# edge-snapshot.sh: one line per host, stable fields only
while read -r h; do
  https=$(curl -s -o /dev/null -w '%{http_code} %{redirect_url}' --connect-timeout 5 --max-time 10 "https://$h/")
  http=$(curl -s -o /dev/null -w '%{http_code} %{redirect_url}' --connect-timeout 5 --max-time 10 "http://$h/")
  cert=$(echo | openssl s_client -connect "$h:443" -servername "$h" 2>/dev/null \
         | openssl x509 -noout -fingerprint -sha256 -enddate 2>/dev/null | tr '\n' ' ')
  hdrs=$(curl -sI --max-time 10 "https://$h/" \
         | grep -iE '^(strict-transport-security|server|x-content-type-options|referrer-policy):' | tr -d '\r' | sort | tr '\n' ';')
  echo "$h | https=$https | http=$http | $cert | $hdrs"
done < hosts.txt
./edge-snapshot.sh > before.txt
# ... make the change ...
./edge-snapshot.sh > after.txt && diff before.txt after.txt && echo IDENTICAL

Include wildcard subdomains and hosts served by other routers in hosts.txt. That’s where surprises hide.


Step 1: Upgrade to Traefik v3

v3 has real breaking changes. On Docker Swarm, the ones that bite most often:

v2 v3
--providers.docker.swarmMode=true --providers.swarm.endpoint=… (separate provider)
HostRegexp(`{sub:[a-z]+}.example.com`) HostRegexp(`^[a-z]+\.example\.com$`) (plain Go regex)
HostRegexp(`a`, `b`) / Host(`a`, `b`) one argument each, joined with ||
traefik.docker.network labels traefik.swarm.network
…dnschallenge.delaybeforecheck …dnschallenge.propagation.delayBeforeChecks
level=error log lines ERR, with ANSI colors by default (--log.nocolor=true)

Dry-run v3 against your live labels

You can see exactly which routers v3 will reject before any downtime. Start a throwaway v3 container that reads your real service labels, with its dashboard bound to localhost and ACME pointed at Let’s Encrypt staging with temporary storage (so it can’t touch real certificates):

docker run --rm -d --name traefik-v3-dryrun \
  -v /var/run/docker.sock:/var/run/docker.sock:ro \
  -p 127.0.0.1:18089:8080 \
  traefik:v3.x.y \
  --api.insecure=true \
  --providers.swarm.endpoint=unix:///var/run/docker.sock \
  --providers.swarm.exposedbydefault=false \
  --entryPoints.http.address=:80 --entryPoints.https.address=:443 \
  --certificatesresolvers.le.acme.caserver=https://acme-staging-v02.api.letsencrypt.org/directory \
  --certificatesresolvers.le.acme.storage=/tmp/le.json \
  --certificatesresolvers.le.acme.tlschallenge=true
sleep 20
curl -s 127.0.0.1:18089/api/http/routers \
  | jq -r '.[] | select(.status!="enabled") | "\(.name): \(.error // [] | join("; "))"'
docker stop traefik-v3-dryrun

Every line printed is a router you must fix. You can also load your new rules into the dry run via a file provider, to prove they parse before you edit production.

One more thing for stack files. Regex anchors like $ must be written as $$ in Compose/Swarm files, or they’re treated as variable references. Keep label lines unquoted or single-quoted, because double quotes make \. an invalid YAML escape. Verify with docker stack config -c stack.yml, which prints the rendered values.


Step 2: Rehearse the socket proxy

Before touching production, prove the proxy blocks what it should:

docker network create proxytest
docker run -d --rm --name socket-proxy --network proxytest \
  -v /var/run/docker.sock:/var/run/docker.sock:ro \
  -e SERVICES=1 -e TASKS=1 -e NETWORKS=1 -e NODES=1 \
  tecnativa/docker-socket-proxy

for path in services tasks networks nodes containers/json images/json secrets; do
  printf '%-16s %s\n' "$path" \
    "$(docker run --rm --network proxytest curlimages/curl -s -o /dev/null -w '%{http_code}' http://socket-proxy:2375/$path)"
done
printf '%-16s %s\n' "POST create" \
  "$(docker run --rm --network proxytest curlimages/curl -s -o /dev/null -w '%{http_code}' -X POST http://socket-proxy:2375/containers/create)"
services         200
tasks            200
networks         200
nodes            200
containers/json  403
images/json      403
secrets          403
POST create      403

Then rehearse non-root Traefik through the proxy on the same test network. Start it with --user 65532:65532, point it at tcp://socket-proxy:2375, and bind entrypoints to :8000/:8443. Confirm three things:

docker exec traefik-test id                              # uid=65532
docker exec traefik-test traefik healthcheck --ping      # OK
curl -s 127.0.0.1:18089/api/http/routers | jq -r '.[] | "\(.status)\t\(.name)"'   # every router enabled

If Traefik logs 403 for an endpoint it needs, add only that permission to the proxy, and nothing broader.


Step 3: The production configuration

Swarm stack (Compose is similar: use --providers.docker.endpoint and allow CONTAINERS=1 instead of services/tasks):

networks:
  public:
    external: true            # existing network, unchanged
  socket_proxy:
    driver: overlay
    internal: true            # no internet access

services:
  socket-proxy:
    image: tecnativa/docker-socket-proxy@sha256:<pin-the-digest>
    environment: { SERVICES: 1, TASKS: 1, NETWORKS: 1, NODES: 1 }
    volumes:
      - /var/run/docker.sock:/var/run/docker.sock:ro
    networks: [socket_proxy]
    deploy:
      placement:
        constraints: [node.role == manager]

  traefik:
    image: traefik:v3.x.y
    user: "65532:65532"
    ports:                                    # public 80/443 → internal 8000/8443
      - { target: 8000, published: 80,  protocol: tcp, mode: host }
      - { target: 8443, published: 443, protocol: tcp, mode: host }
    networks: [public, socket_proxy]          # add the private one, keep the rest
    volumes:                                  # no docker.sock, other mounts unchanged
      - /srv/traefik/certificates:/certificates
    command:
      - --providers.swarm.endpoint=tcp://socket-proxy:2375
      - --entryPoints.http.address=:8000
      - --entryPoints.https.address=:8443
      # ACME, file provider and the rest as before

I also added a healthcheck, traefik healthcheck --ping, which needs --ping=true.

Things that matter here:

  • Add networks, don’t replace them. If Traefik’s networks: list ends up containing only socket_proxy, it can no longer reach your apps.
  • Non-root processes can’t bind ports below 1024, so Traefik listens on 8000/8443 and Docker publishes them as 80/443.
  • Watch redirect ports. If you redirect HTTP→HTTPS with entrypoint redirection set to to=https, the redirect URL will include :8443. Use to=:443, or a redirectScheme middleware.
  • Pin the proxy image by digest. It’s the one component that still holds the socket.

Permissions

The certificate storage must be writable by the new user:

sudo chown 65532:65532 /srv/traefik/certificates /srv/traefik/certificates/*.json
sudo chmod 700 /srv/traefik/certificates && sudo chmod 600 /srv/traefik/certificates/*.json

docker run --rm --user 65532:65532 -v /srv/traefik/certificates:/certificates --entrypoint sh traefik:v3.x.y \
  -c 'test -w /certificates/acme.json && echo "writable by 65532"'

This is rollback-safe, because a root Traefik can still read files owned by another user.

Review what actually changes

Diff the rendered stack, not the file you edited:

docker stack config -c stack.yml           > render-live.yml
docker stack config -c stack.candidate.yml > render-candidate.yml
diff render-live.yml render-candidate.yml

Comments, whitespace, and formatting disappear, so only real changes remain. Any unexpected line is a mistake caught before deploy.


Step 4: Cut over and verify

cp stack.yml stack.yml.bak
cp stack.candidate.yml stack.yml
docker stack deploy -c stack.yml mystack

Only Traefik is replaced (and the proxy added); other services don’t restart because their definitions didn’t change. With host-mode ports, expect under a minute of downtime per deploy.

On the server:

docker inspect $(docker ps -q -f name=mystack_traefik) \
  --format 'user={{.Config.User}} health={{.State.Health.Status}} mounts={{range .Mounts}}{{.Source}} {{end}}'
# user=65532:65532 health=healthy mounts=/srv/traefik/certificates /srv/traefik/dynamic

From outside:

./edge-snapshot.sh > after.txt && diff before.txt after.txt && echo IDENTICAL
curl -sI http://example.com | grep -i '^location'     # no :8443

Rollback is the previous stack file, plus removing the proxy (docker stack deploy doesn’t remove services that were dropped from the file):

cp stack.yml.bak stack.yml && docker stack deploy -c stack.yml mystack
docker service rm mystack_socket-proxy

Three things my checks missed

1. A rule can be enabled and still never match

The dry run flagged one router, a wildcard with v2 regex syntax. The catch-all rule, HostRegexp(`{host:.+}`), had the same kind of syntax but showed as enabled. v3 read it as a literal regular expression that requires the text {host: in the hostname, so it would never match, and the HTTP→HTTPS redirect for every site would have silently stopped. The v3 form is HostRegexp(`.+`).

2. Rewriting a rule reordered my routing

This one reached production. When a router has no explicit priority, Traefik ranks it by the length of its rule. The rewritten wildcard rule came out around 110 characters, so it outranked a subdomain router with priority=100, and after the cutover that subdomain returned 404 from the wildcard app. The dry run couldn’t see it; the edge diff did. Give wildcard routers an explicit low priority:

- traefik.http.routers.wildcard.priority=1

3. The error grep that missed the errors

v2 writes level=error. v3 writes ERR, colored with ANSI codes by default, so a plain grep for ERR matches nothing. I strip the codes in the grep and run production with --log.nocolor=true.


Results

Before After
Traefik version 2.x (years old) v3, current
Known HIGH/CRITICAL vulnerabilities in the Traefik image 87 2 (one CVE listed for two OS packages, in a library Traefik doesn’t use)
Internet-facing process with Docker API access Yes, full API None (read-only allowlist behind an internal network)
Traefik runs as root uid 65532
Docker socket mounted in Traefik Yes No
Container healthcheck None Yes
Routing behavior (every public host) baseline Identical after the priority fix (diff verified)
Downtime Under two minutes, across two cutovers

Lessons

  1. A read-only socket mount protects nothing. Put an allowlist proxy in between.
  2. Rehearse in throwaway containers against your live configuration. It shows what will break with zero downtime.
  3. Diff the rendered configuration, and diff the edge from outside. Each caught something the other missed.
  4. Least privilege is layered: non-root, no socket, a private network, a read-only API, and secrets that never appear in API responses.

Read-only still exposes environment variables

A socket proxy that allows reading services also allows reading service definitions, and those include environment variables. Any database password, API key, or signing secret in a plain environment: entry can be read by a compromised Traefik. Mine had them.

The fix isn’t in the proxy. It’s in where you keep secrets: the orchestrator’s secrets store, mounted as files and referenced by _FILE variables, so service definitions only ever contain paths.


What’s next

Every app on this host connected to Postgres as the superuser with the image’s default password, and those credentials sat in environment: blocks. Part 3 is how I fixed both.