Dev.to Security 🔐 Cybersecurity 👁 0 📖 13 min read

Stop Running as Root for One Port: Practical Linux Capabilities

A web service needs to bind port 80. Somewhere in the deployment notes that becomes User=root. One line, and the entire process — its HTTP parser, its TLS library, its template engine, every package in the lockfile — now

A web service needs to bind port 80. Somewhere in the deployment notes that becomes User=root. One line, and the entire process — its HTTP parser, its TLS library, its template engine, every package in the lockfile — now runs with every privilege the kernel can grant. The bind() call needed exactly one of them.

Linux has had a mechanism for this since 2.2: capabilities. Instead of one all-or-nothing root uid, the kernel checks a set of independent privilege bits for each privileged operation. CAP_NET_BIND_SERVICE covers binding ports below 1024. CAP_NET_RAW covers raw sockets. CAP_DAC_READ_SEARCH covers bypassing file read checks. There are 41 of them on a current 6.12 kernel, and a process can hold a subset.

The mechanism works. Configuring it is where people get surprised. setcap returns 0, getcap prints the capability you asked for, and the service still dies with EACCES. Nothing lied; the capability was attached to the file. It just never reached the process's effective set.

This article is about the gap between those two statements.

Root is a uid that holds every capability

Permission checks in the kernel do not ask "is this process root?" They ask "does this thread have the required capability in its effective set?" By default, root is special only because uid 0 starts with all capabilities, and execve() re-grants them for uid 0.

Capabilities are per-thread, not per-process. A process's main thread is what /proc/PID/status shows; individual threads have their own sets under /proc/PID/task/TID/status.

This matters because dropping root is not the same as dropping capabilities. A service can run as www-data and still hold CAP_NET_ADMIN if someone grants it deliberately. Conversely, a root process can have CAP_SYS_ADMIN removed from its bounding set and become much less dangerous while still being uid 0.

The five sets

Every thread carries five capability sets. The names are old, and the interactions are where the bugs live.

Set Purpose Across execve()
Permitted Ceiling on what the thread may put in its effective set Cleared for non-root unless file capabilities or ambient caps add to it
Effective The set the kernel actually checks Rebuilt from permitted, file effective bit, and ambient
Inheritable Capabilities preserved for the next program Preserved unchanged; used (ANDed with the file's inheritable set) to build the new permitted set
Bounding Hard ceiling on capabilities a file may grant Preserved; per-thread since Linux 2.6.25
Ambient Caps preserved across execve() of an unprivileged file Preserved unless the file is privileged; since Linux 4.3

Two invariants are worth memorizing:

  1. Ambient capabilities must be a subset of both permitted and inheritable. You cannot make a capability ambient if the thread does not already hold it in those two sets.
  2. The bounding set masks file permitted capabilities, but not file inheritable capabilities. A capability kept in the inheritable set outside the bounding set can still be gained from a file's inheritable set.

File capabilities live in an extended attribute named security.capability and require CAP_SETFCAP to write. They have three parts: permitted, inheritable, and a single effective bit. The effective bit is not a set; it says "raise all newly permitted file capabilities into the effective set at exec."

The execve algebra

The kernel's transformation is short enough to read directly. From capabilities(7):

P'(ambient)   = (file is privileged) ? 0 : P(ambient)

P'(permitted) = (P(inheritable) & F(inheritable)) |
                (F(permitted) & P(bounding)) |
                P'(ambient)

P'(effective) = F(effective) ? P'(permitted) : P'(ambient)

P'(inheritable) = P(inheritable)
P'(bounding)    = P(bounding)

Read the effective line carefully. If the file's effective bit is clear, the new effective set is only the ambient set. Permitted capabilities that came from the file stay permitted but do nothing. That is why setcap cap_net_bind_service=p produces a process that holds the capability and still cannot bind port 80.

A file is "privileged" for this purpose if it has any file capabilities, or has the set-user-ID or set-group-ID bit set. Executing a privileged file clears the ambient set.

Another line from the same man page matters for services: if a process with nonzero user IDs calls execve(), capabilities in its permitted and effective sets are cleared. Running as www-data and hoping a capability survives from the parent shell does not work. You need file capabilities or ambient capabilities.

Read the caps of anything running

Before changing anything, look at what a process actually holds.

# The five sets for the current shell
grep -E '^Cap(Inh|Prm|Eff|Bnd|Amb):' /proc/self/status

# Decode a hex mask into names
capsh --decode=0x0000000000000400

# The caps of a running service
getpcaps "$(systemctl show -p MainPID --value nginx.service)"

On a 6.12 kernel the output looks like this:

0x0000000000000400=cap_net_bind_service

The masks are plain bitmaps: bit 10 is CAP_NET_BIND_SERVICE, so 0x400. The full default bounding set on that kernel is 0x000001ffffffffff — 41 bits, capabilities 0 through 40. You do not need to count bits by hand:

systemd-analyze capability CAP_NET_BIND_SERVICE
# NAME                 NUMBER
# cap_net_bind_service     10

systemd-analyze capability with no argument prints the whole table.

Lab: one binary, six ways to fail

The test program is deliberately small: bind 127.0.0.1:80, print the result, print the capability sets, exit. Nothing listens; the socket closes immediately.

#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

static void show_caps(void) {
    FILE *f = fopen("/proc/self/status", "r");
    char line[256];
    if (!f) return;
    while (fgets(line, sizeof line, f)) {
        if (!strncmp(line, "CapPrm:", 7) || !strncmp(line, "CapEff:", 7) ||
            !strncmp(line, "CapBnd:", 7) || !strncmp(line, "CapAmb:", 7))
            fputs(line, stdout);
    }
    fclose(f);
}

int main(void) {
    int s = socket(AF_INET, SOCK_STREAM, 0);
    int one = 1;
    setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &one, sizeof one);

    struct sockaddr_in a = {0};
    a.sin_family = AF_INET;
    a.sin_port = htons(80);
    inet_pton(AF_INET, "127.0.0.1", &a.sin_addr);

    printf("uid=%d\n", getuid());
    if (bind(s, (struct sockaddr *)&a, sizeof a) == 0)
        printf("bind 127.0.0.1:80 OK\n");
    else
        printf("bind 127.0.0.1:80 FAIL errno=%d %s\n", errno, strerror(errno));

    show_caps();
    close(s);
    return 0;
}

Build it as an ordinary user:

gcc -O2 -Wall -o server server.c
./server
uid=1000
bind 127.0.0.1:80 FAIL errno=13 Permission denied
CapPrm: 0000000000000000
CapEff: 0000000000000000
CapBnd: 000001ffffffffff
CapAmb: 0000000000000000

The bounding set is full. Permitted and effective are empty. The kernel checked the effective set and said no.

Failure one: the nosuid mount

Attach the capability to the file:

sudo setcap cap_net_bind_service=ep ./server
getcap ./server
# ./server cap_net_bind_service=ep
./server

On my first attempt this still failed, with the same EACCES, and CapPrm still zero. The binary was in /tmp, and /tmp was mounted nosuid:

$ findmnt -no TARGET,OPTIONS /tmp
/tmp rw,nosuid,nodev,nr_inodes=1048576,inode64

File capabilities are ignored for the same reasons set-user-ID bits are ignored. setcap does not warn. getcap still reports the xattr, because the xattr is really there. execve() treats the file as if it had no capabilities.

Moving the same binary to a normal filesystem fixed it:

$ getcap ./server
./server cap_net_bind_service=ep
$ ./server
uid=1000
bind 127.0.0.1:80 OK
CapPrm: 0000000000000400
CapEff: 0000000000000400
CapBnd: 000001ffffffffff
CapAmb: 0000000000000000

Failure two: permitted without effective

Now change the file capability from +ep to +p:

sudo setcap cap_net_bind_service=p ./server
getcap ./server
# ./server cap_net_bind_service=p
./server
uid=1000
bind 127.0.0.1:80 FAIL errno=13 Permission denied
CapPrm: 0000000000000400
CapEff: 0000000000000000
CapBnd: 000001ffffffffff
CapAmb: 0000000000000000

The capability is in the permitted set. The effective set is empty, so the bind is still denied. This is the clearest demonstration of the difference between the two sets: permitted is a ceiling, effective is what the kernel uses.

Failure three: bounding set alone

With systemd, the same pattern appears from the other direction. Grant only a bounding set to a non-root service:

sudo systemd-run --wait --pipe --collect \
  -p User=debian \
  -p CapabilityBoundingSet=CAP_NET_BIND_SERVICE \
  /home/debian/capdemo/server
bind 127.0.0.1:80 FAIL errno=13 Permission denied
CapPrm: 0000000000000000
CapEff: 0000000000000000
CapBnd: 0000000000000400
CapAmb: 0000000000000000

The bounding set is now exactly CAP_NET_BIND_SERVICE, and the process still has nothing usable. Bounding only limits what may be gained; it does not grant anything. For a non-root service there are no file capabilities and no ambient caps, so exec starts from an empty permitted set.

Add ambient capabilities and it works:

sudo systemd-run --wait --pipe --collect \
  -p User=debian \
  -p CapabilityBoundingSet=CAP_NET_BIND_SERVICE \
  -p AmbientCapabilities=CAP_NET_BIND_SERVICE \
  /home/debian/capdemo/server
bind 127.0.0.1:80 OK
CapPrm: 0000000000000400
CapEff: 0000000000000400
CapBnd: 0000000000000400
CapAmb: 0000000000000400

All four sets contain only CAP_NET_BIND_SERVICE. That is the shape you want.

The one that surprised me

NoNewPrivileges=yes is standard hardening, and it does not break systemd's ambient capabilities:

sudo systemd-run --wait --pipe --collect \
  -p User=debian \
  -p NoNewPrivileges=yes \
  -p CapabilityBoundingSet=CAP_NET_BIND_SERVICE \
  -p AmbientCapabilities=CAP_NET_BIND_SERVICE \
  /home/debian/capdemo/server
bind 127.0.0.1:80 OK
CapPrm: 0000000000000400
CapEff: 0000000000000400
CapBnd: 0000000000000400
CapAmb: 0000000000000400

The reason is that the ambient capability was granted to the process before execve(), not gained during it. NoNewPrivileges blocks gaining new privileges through execve() — setuid bits and file capabilities. It does not strip capabilities that are already in the permitted set.

The contrast is worth testing. With file capabilities on the binary and no ambient grant, NoNewPrivileges=yes blocks the capability entirely:

sudo setcap cap_net_bind_service=ep ./server
sudo systemd-run ... -p User=debian -p NoNewPrivileges=yes ./server
→ bind FAIL, CapPrm 0000000000000000

Same binary, same file capability, one boolean apart.

The results in one table

Launch path CapPrm CapEff CapAmb bind :80
uid 1000, no caps 0 0 0 EACCES
setcap +ep on /tmp (nosuid) 0 0 0 EACCES
setcap +ep on /home 0x400 0x400 0 OK
setcap +p on /home 0x400 0 0 EACCES
systemd, bounding only 0 0 0 EACCES
systemd, bounding + ambient 0x400 0x400 0x400 OK
same, plus NoNewPrivileges=yes 0x400 0x400 0x400 OK
file caps, NoNewPrivileges=yes, no ambient 0 0 0 EACCES

Tested on Debian 13, kernel 6.12.117, systemd 257. The masks are specific to that kernel's capability count; the behavior is not.

The unit that works

For a service that needs to bind port 80 and nothing else:

[Unit]
Description=Example web service on port 80
After=network-online.target
Wants=network-online.target

[Service]
Type=simple
User=www-data
Group=www-data
ExecStart=/usr/local/bin/webapp --listen 0.0.0.0:80

AmbientCapabilities=CAP_NET_BIND_SERVICE
CapabilityBoundingSet=CAP_NET_BIND_SERVICE
NoNewPrivileges=yes

RestrictAddressFamilies=AF_INET AF_INET6
ProtectSystem=strict
ProtectHome=yes
PrivateTmp=yes
PrivateDevices=yes
StandardOutput=journal
StandardError=journal

[Install]
WantedBy=multi-user.target

The two capability lines do different jobs and you need both:

  • CapabilityBoundingSet=CAP_NET_BIND_SERVICE removes every other capability from the ceiling. Even if the binary later executes something with file capabilities, it cannot gain them.
  • AmbientCapabilities=CAP_NET_BIND_SERVICE puts the capability into the permitted, effective, and ambient sets after the switch to www-data. systemd also adds keep-caps to SecureBits= automatically so the capability survives the uid change.

NoNewPrivileges=yes then prevents the service and its children from gaining anything else through execve(). Notes on the unit:

  • User=www-data exists on Debian and Ubuntu. Create a dedicated user in production; do not share one across unrelated services.
  • ProtectSystem=strict makes the whole filesystem read-only except /dev, /proc, and /sys. If the app writes under /var/lib/webapp, add StateDirectory=webapp and let systemd create it with the right ownership.
  • RestrictAddressFamilies=AF_INET AF_INET6 is enough for a TCP listener. Add AF_UNIX if the app talks to a local socket.
  • The unit syntax-checks with systemd-analyze verify; on a test box the only complaint was that the demo binary /usr/local/bin/webapp did not exist yet.

If the application supports socket activation, there is an even smaller option: a .socket unit binds port 80 as PID 1 and passes the listening descriptor to the service, which then needs no capabilities at all. That is a different design with different trade-offs, and it only helps if the app can accept an inherited socket.

File capabilities: useful, fragile

AmbientCapabilities= is the right tool for a systemd service. File capabilities are the right tool for a binary that has to be launched some other way: from cron, from a shell, or by a vendor's own supervisor.

sudo setcap cap_net_bind_service=ep /usr/local/bin/webapp
getcap /usr/local/bin/webapp
# /usr/local/bin/webapp cap_net_bind_service=ep

# Remove them
sudo setcap -r /usr/local/bin/webapp

The syntax is a capability list plus set flags: e for effective, p for permitted, i for inheritable. +ep is the common case for a binary that was not written against libcap.

Then the failure modes:

Writing the file clears the capability. On a throwaway copy:

sudo setcap cap_net_bind_service=ep ./server
printf '\0' | sudo tee -a ./server >/dev/null
getcap ./server
# no output

Any write or truncate removes security.capability, just as it removes setuid bits. If your deploy process rewrites the binary in place, it must re-apply setcap afterwards.

Copying loses it unless you preserve xattrs. A plain cp dropped the capability. cp -a and cp --preserve=all, run as root, kept it. In a deploy script, the safest rule is to re-apply setcap after the copy and verify with getcap; do not assume the archive or package step preserved the xattr.

nosuid mounts ignore it silently. As seen above. Check findmnt -no OPTIONS on the filesystem holding the binary.

Scripts do not get file capabilities. This one is easy to miss because setcap succeeds on a shell script and getcap shows the capability. I tested it: a #!/bin/sh wrapper with cap_net_bind_service=ep ran its target with CapPrm zero and the bind failed. The kernel applies file capabilities to the binary passed to execve(); for a script, that binary is the interpreter, not the script.

Capability-dumb binaries can fail with EPERM. If a file has capabilities but the program does not use libcap, and the bounding set masks one of those file capabilities, execve() fails with EPERM instead of running with less privilege. It is a safety check: the program cannot notice that it did not get what the file promised. If a service suddenly refuses to start after you tighten CapabilityBoundingSet=, this is a likely reason.

What capabilities are not

Capabilities divide root's power; they do not sandbox a process.

  • They do not restrict filesystem paths. A process with CAP_DAC_READ_SEARCH can read files it has no business reading. Path-based confinement is Landlock's job.
  • They do not filter system calls. That is seccomp.
  • They do not restrict network destinations. That is nftables or IPAddressAllow=.
  • CAP_SYS_ADMIN is effectively root in one bit. The man page calls it "the new root" and tells kernel developers not to add to it. Never grant it as a shortcut; find the narrow capability the operation actually needs.
  • CAP_SYS_PTRACE can read and write another process's memory. CAP_NET_RAW can sniff and spoof traffic on the host. CAP_NET_BIND_SERVICE is narrow, but it still lets the process impersonate any low-port service on that machine.

Combine capabilities with the other layers rather than treating them as a replacement. systemd-analyze security <unit> scores a unit's exposure and names the capability lines it dislikes:

✗ CapabilityBoundingSet=~CAP_NET_(BIND_SERVICE|BROADCAST|RAW) Service has elevated networking privileges   0.1
✗ CapabilityBoundingSet=~CAP_SYS_ADMIN                        Service has administrator privileges            0.3

It is a blunt score, but it is a useful checklist for finding a service that still has the default full bounding set.

One alternative worth knowing

If the only reason for the capability is "port 80 is below 1024", and you control the network namespace, the kernel has a sysctl for that:

sysctl net.ipv4.ip_unprivileged_port_start
# net.ipv4.ip_unprivileged_port_start = 1024

sudo sysctl -w net.ipv4.ip_unprivileged_port_start=80

The default is 1024. Setting it to 80 makes ports 80 and above unprivileged for every process in that network namespace; setting it to 0 makes all ports unprivileged. It is per-namespace, which makes it attractive in containers, and it is a much broader grant than one capability on one service. Use it when you want the policy to be "low ports are normal here", not when you want to fix one daemon.

Checklist

  1. Find the actual privileged operation. Binding a port, opening a raw socket, reading a protected file, setting the clock — each maps to a specific capability.
  2. Run the service as a dedicated non-root user.
  3. In the unit, set CapabilityBoundingSet= to only that capability and AmbientCapabilities= to the same one.
  4. Add NoNewPrivileges=yes. It does not remove ambient capabilities and it blocks file-capability and setuid gains.
  5. Verify from inside the running service: grep Cap /proc/PID/status, or getpcaps PID. Do not trust the unit file; trust the masks.
  6. If you use file capabilities instead, put the binary on a non-nosuid filesystem, use +ep, re-apply after every write or copy, and verify with getcap.
  7. Add seccomp, Landlock, and network filtering for the parts capabilities cannot express.

The bind syscall needs one bit. Grant that bit, not the whole uid.

Sources

📰 Read the original article on Dev.to Security

Originally published by Dev.to Security. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.