Audit Linux capabilities and test least-privilege service access
A network diagnostic tool only needs to create raw sockets, yet it is configured to run as root indefinitely—a common case of excessive privileges on dedicated servers. Switching to an ordinary account and then applying setcap directly can spread those privileges to a shared interpreter. A reliable approach is to inventory file capabilities first, demonstrate that access fails without authorization and succeeds with a single capability, then confine that authorization to the intended service.
The examples below use Debian 12 and require administrator privileges, systemd, Python 3, and libcap2-bin. The test only creates sockets: it sends no packets and does not modify production network interfaces. Login credentials for an Epon dedicated server are available in the console after payment; all operations in this article take place inside the system after connecting over SSH.
1. Distinguish file capabilities from process capabilities
Linux capabilities split some root privileges into individual capabilities. CAP_NET_RAW permits the creation of raw sockets, but it does not grant full network administration privileges. File capabilities are stored in extended attributes; the capabilities a process actually holds also depend on its execution identity, capability sets, and startup restrictions.
CapabilityBoundingSet defines a ceiling on capabilities; it does not grant them on its own. AmbientCapabilities allows specified capabilities to survive the execution of ordinary programs, making it suitable for non-root services started by systemd. Both settings must be checked together. The mere presence of a configuration line does not prove that the intended boundary is enforced.
Do not set file capabilities directly on
/usr/bin/python3, a shell, or another shared interpreter. Authorization attached to an interpreter cannot distinguish “only this script is allowed to use it.”
NoNewPrivileges=yes is not a switch that clears privileges, either. It restricts the acquisition of new privileges through subsequent program execution; it does not revoke capabilities already held, nor does it replace file ownership controls and protection of the execution entry point.
2. Start with a reviewable file inventory
After installing the tools, save the inventory in a protected directory. The following commands scan only common program directories. If software is deployed on other mount points, scan those separately; these results must not be described as a full-system audit.
sudo apt-get install libcap2-bin python3
sudo install -d -m 0700 /root/cap-audit
sudo sh -c 'getcap -r /usr /opt > /root/cap-audit/files.txt 2> /root/cap-audit/errors.txt'
sudo cat /root/cap-audit/files.txt
sudo cat /root/cap-audit/errors.txt
For each entry, record the path, capabilities, owning package, and operational purpose. Use dpkg-query -S to identify the package and readlink -f to resolve the actual executable. Scan errors must be explained, not treated as an absence of findings.
An empty file-capability inventory does not mean there are no paths to privilege escalation. Continue by inventorying setuid files and review them separately; do not conflate the two result sets:
sudo find /usr /opt -xdev -type f -perm -4000 -print
Do not run setcap -r in bulk. If you find an anomaly, first preserve the original attributes, package information, and approval records, then decide whether to revoke the capabilities or reinstall the package. Otherwise, you may break legitimate tools while also destroying evidence.
3. Verify denial and authorization in an isolated network
Create a probe owned by the administrator that ordinary accounts can read but not modify. It prints its effective identity and capability sets, then attempts to open a raw socket. Permission denial produces exit code 77; success produces 0. Any other exception remains a test failure rather than being disguised as an expected denial.
sudo tee /run/cap-probe.py > /dev/null <<'PY'
import os
import socket
print("uid", os.getuid(), flush=True)
with open("/proc/self/status", encoding="ascii") as status:
for line in status:
if line.startswith(("Cap", "NoNewPrivs:")):
print(line.strip(), flush=True)
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_ICMP)
except PermissionError:
print("raw_socket=denied", flush=True)
raise SystemExit(77)
else:
sock.close()
print("raw_socket=opened", flush=True)
PY
sudo chmod 0644 /run/cap-probe.py
Run a negative test without capabilities first
DynamicUser assigns a temporary non-root identity, while PrivateNetwork creates a separate network namespace. The empty assignments below explicitly clear both capability settings:
sudo systemd-run --unit=cap-probe-denied --wait --pipe --collect \
-p DynamicUser=yes \
-p PrivateNetwork=yes \
-p NoNewPrivileges=yes \
-p 'CapabilityBoundingSet=' \
-p 'AmbientCapabilities=' \
/usr/bin/python3 /run/cap-probe.py
Expect a nonzero UID, raw_socket=denied, and a unit report showing exit code 77. If the operation succeeds, stop the acceptance check and inspect the interpreter’s attributes, the effective configuration, and the security environment. Failure to create the namespace must not count as a successful permission-denial test, either.
Then grant a single capability
sudo systemd-run --unit=cap-probe-allowed --wait --pipe --collect \
-p DynamicUser=yes \
-p PrivateNetwork=yes \
-p NoNewPrivileges=yes \
-p CapabilityBoundingSet=CAP_NET_RAW \
-p AmbientCapabilities=CAP_NET_RAW \
/usr/bin/python3 /run/cap-probe.py
The identity should still be non-root, but the output should now be raw_socket=opened. Compare CapEff, CapBnd, and CapAmb between the two runs. Hexadecimal values can be decoded with capsh --decode=值, replacing the placeholder with the value. Verify that only the approved capability is present; successful output alone does not prove that authorization is correct.
4. Confine authorization to the service entry point
A successful experiment does not mean the production service needs the same privilege. First confirm that the actual program calls an interface requiring that capability, then use systemctl edit to create an override for the target service:
[Service]
NoNewPrivileges=yes
CapabilityBoundingSet=
CapabilityBoundingSet=CAP_NET_RAW
AmbientCapabilities=
AmbientCapabilities=CAP_NET_RAW
This is only the capability portion of the configuration. The target service must also specify a non-root User and use an administrator-controlled absolute path for startup. The empty assignments clear the existing lists first, preventing additional configuration from inadvertently retaining extra capabilities. If an existing service genuinely depends on other capabilities, document those requirements again rather than blindly overwriting its configuration.
The service account must not be able to modify scripts, module search directories, or startup configuration. Otherwise, an attacker could still replace the code and use the capability. Do not copy PrivateNetwork=yes mechanically into production, either: it isolates the network, and a safeguard used in the experiment may disconnect the real service.
5. Restart, verify, and review after upgrades
Restart the target service as part of a controlled change. Check the actual process identity and /proc/进程号/status, then test the functionality that requires the privilege. If the service has worker processes, inspect each one rather than just the main process. A correct configuration with an unrestarted process is a common source of false passes.
The acceptance record must include at least four items:
- The unauthorized probe was denied, and insufficient permissions were confirmed as the cause.
- The probe with a single capability succeeded, and its capability sets stayed within the approved scope.
- The real service runs as a non-root identity, and both functional checks and denial tests behave as expected.
- After the override was removed and the service restarted, the capability disappeared and operations depending on it were denied again.
Preserve the override configuration, runtime output, and rollback procedure, then delete /run/cap-probe.py. The temporary units use --collect for cleanup, so do not rely on querying them later to retain the test output. Software upgrades may replace files and change their extended attributes. Repeat the inventory rather than assuming an earlier setcap operation remains effective indefinitely.
Least privilege is not achieved merely because a program stops reporting errors. It requires evidence of where authorization is granted, which capabilities it covers, and what happens when it is revoked. The file inventory uncovers hidden grants, the isolated probe tests kernel-enforced boundaries, and the restart review confirms the long-running state. Without all three, there is insufficient evidence that the service’s privileges have been properly confined.
Frequently asked questions
Should CAP_NET_RAW be attached directly to the Python interpreter?
No. File capabilities can affect other scripts launched through that interpreter. Prefer a grant scoped to the intended systemd service and protect its entry point and script ownership.
Does NoNewPrivileges=yes remove capabilities already granted?
No. It prevents gaining new privileges through later executable transitions. Existing and explicitly configured ambient capabilities still require bounding limits and runtime verification.
AMD EPYC 7543P Dedicated Server
From $459/month, with no setup fee or contract.