Install
# Provided by libcap package # RHEL / Alma / Rocky sudo dnf install libcap # Debian / Ubuntu sudo apt install libcap2-bin # openSUSE sudo zypper install libcap-progs # Arch sudo pacman -S libcap
What it does
setcap assigns Linux capabilities to executable files. Capabilities divide traditional root privileges into fine-grained units, allowing programs to perform specific privileged operations without running as root.
How it works (mechanical)
- Writes extended attributes (xattrs) to files.
- Stores capability sets in filesystem metadata.
- Kernel checks capabilities at execution time.
- Reduces need for setuid root binaries.
- Requires filesystem support for extended attributes.
Quick Start
# Allow non-root program to bind to low ports sudo setcap cap_net_bind_service=+ep /usr/bin/myserver
10 Practical Examples
# 1) Grant network bind capability sudo setcap cap_net_bind_service=+ep /usr/bin/python3
# 2) Grant raw network access sudo setcap cap_net_raw=+ep /usr/bin/ping
# 3) Remove all capabilities sudo setcap -r /usr/bin/python3
# 4) View capabilities (using getcap) getcap /usr/bin/python3
# 5) Grant multiple capabilities sudo setcap cap_net_bind_service,cap_net_raw=+ep /usr/bin/app
# 6) Apply to custom binary sudo setcap cap_sys_time=+ep ./timesync
# 7) Verify extended attributes getfattr -d /usr/bin/app
# 8) Compare with traditional setuid chmod u+s /usr/bin/app
# 9) Inspect current user capabilities capsh --print
# 10) Remove specific capability by rewriting sudo setcap cap_net_bind_service=+ep /usr/bin/app
Notes & Gotchas
- Filesystem must support extended attributes (e.g., ext4, xfs).
- Capabilities are lost if file is copied without preserving xattrs.
- More secure than setuid in many cases.
- Incorrect use can create security risks.
- Use
getcapto inspect existing capabilities.
Historical Context
Linux capabilities were introduced to break root privileges into smaller units, improving security. setcap became the primary tool to assign these capabilities to executables.
Modern Equivalent
Capabilities remain part of modern Linux security models and are commonly used in container environments and system services to reduce privilege scope.
Related Commands
- getcap — display file capabilities.
- capsh — manipulate process capabilities.
- chmod — change file permissions.
- setfacl — manage access control lists.
- chown — change file ownership.