Users, permissions and capabilities

How Linux decides who may do what: UIDs and groups, permission bits, setuid and sudo, and Linux capabilities as the way to give a process one slice of root instead of all of it.

FREEBy ·Lesson·12 min read·Beginner → Intermediate
Linux permissionssetuidsudoLinux capabilitiesCAP_SYS_ADMINno_new_privs

01Users, groups and the kernel's view of identity

✓What you will learn
  • Explain how the kernel identifies a process using UIDs, GIDs and supplementary groups
  • Read and set permission bits, including what they mean on directories
  • Explain why setuid binaries and loose sudo rules are classic privilege escalation paths
  • Replace "run as root" with specific Linux capabilities and NoNewPrivileges

The kernel does not know user names. It knows numbers. Every process carries a real UID (who started it), an effective UID (whose permissions it uses right now), a saved UID, a primary GID and a list of supplementary groups. /etc/passwd maps names to numbers; password hashes live in /etc/shadow, which only root (and on some distributions the shadow group) can read. UID 0 is root, and historically the kernel skipped almost every permission check for it.

Identity as the kernel sees itbash
$ id
uid=1000(alice) gid=1000(alice) groups=1000(alice),27(sudo),998(docker)

$ grep alice /etc/passwd
alice:x:1000:1000:Alice,,,:/home/alice:/bin/bash   # "x" means the hash is in /etc/shadow

$ grep -E '^(Uid|Gid|CapEff)' /proc/self/status     # what the kernel actually checks
Uid:  1000  1000  1000  1000                         # real, effective, saved, filesystem
Gid:  1000  1000  1000  1000
CapEff: 0000000000000000                             # no capabilities: an ordinary process
!Some groups are root in disguise

Membership of docker lets a user start a container that mounts / from the host, which is root on the host. disk gives raw read access to block devices, and on many systems adm reads every log. Audit group membership as carefully as sudo rules.

02Permission bits, umask and ACLs

Every file has an owner, a group and nine permission bits: read, write and execute for user, group and other. The kernel checks exactly one of those three sets, the first that matches, so a file that is ---rwxrwx denies its own owner. On a directory the bits mean something different, and this is where most mistakes happen.

BitOn a fileOn a directory
r (4)Read contentsList names in it
w (2)Modify contentsCreate, rename and delete entries, even files you do not own
x (1)ExecuteTraverse: open files inside if you know the name
setuid (4000)Run with the file owner's effective UIDIgnored on Linux
setgid (2000)Run with the file's groupNew files inherit the directory's group
sticky (1000)Ignored on LinuxOnly an entry's owner (or root) may delete or rename it, as on /tmp (mode 1777)

The umask removes bits from the mode a program asks for when creating files. The usual 022 gives 644 files and 755 directories, readable by every local user. Services that write secrets should run with 077 (systemd: UMask=0077) so new files are private by default. When owner, group and other are not enough, POSIX ACLs add named entries: setfacl -m u:backup:r /srv/db.conf, inspected with getfacl. A + at the end of the mode in ls -l tells you an ACL exists.

iWrite on the directory beats read-only on the file

If an attacker can write to a directory, they can delete your root-owned, mode 444 config file and create a new one with the same name. Protect the directory, not just the file. This is also why a writable directory early in a service's PATH is a privilege escalation.

03setuid, sudo and how privilege escalation usually happens

A setuid program runs with its owner's effective UID regardless of who starts it. passwd is setuid root because an ordinary user must be able to update /etc/shadow. Every setuid-root binary is therefore a program that takes input from unprivileged users and runs as root: any bug in it is a local privilege escalation. PwnKit (CVE-2021-4034) was a memory-corruption bug in polkit's setuid pkexec, present on most distributions for over a decade.

sudo is a setuid-root program with a policy file. It records who ran what, which is its main advantage over shared root passwords. The policy is where things go wrong: allowing a user to run an editor, a pager, find, tar or a scripting interpreter as root is effectively full root, because each of these can spawn a shell. The GTFOBins project catalogues hundreds of such escapes.

Finding the usual escalation pathsbash
# Inventory setuid and setgid binaries, then compare against a known-good baseline
find / -xdev -type f \( -perm -4000 -o -perm -2000 \) -printf '%m %u %p\n' 2>/dev/null | sort

# What may the current user run as root?
sudo -l

# Risky sudoers lines (any of these is root):
#   alice ALL=(root) NOPASSWD: /usr/bin/vim        -> :!sh
#   alice ALL=(root) /usr/bin/find                 -> find . -exec /bin/sh \;
#   deploy ALL=(root) /opt/app/deploy.sh           -> fine only if deploy.sh and its directory are root-owned and not writable by deploy
  • Edit sudoers with `visudo`, which syntax-checks before saving. A broken sudoers file can lock everyone out of root.
  • Allow specific commands with fixed arguments, never interpreters or editors. For editing, use sudoedit, which edits a copy as the user and writes it back.
  • Scripts run via sudo must be owned by root, in a root-owned directory, and must not read environment variables or relative paths the caller controls.
  • Patch sudo itself: Baron Samedit (CVE-2021-3156) was a heap overflow in sudo's argument parsing that gave root to any local user, sudoers entry or not.

04Capabilities: a slice of root instead of all of it

Since Linux 2.2 the kernel has split root's power into capabilities, about forty of them today. Instead of checking "is the UID 0", the kernel checks "does this process hold CAP_NET_BIND_SERVICE" before letting it bind port 443. A web server that needs only that capability does not need to be root, and a bug in it no longer means full control of the host.

CapabilityWhat it allowsRisk if granted
CAP_NET_BIND_SERVICEBind ports below 1024Low: the usual reason services run as root
CAP_NET_RAWRaw and packet sockets (ping, packet capture)Medium: spoofing and sniffing on the host's interfaces
CAP_DAC_OVERRIDEBypass file read, write and execute permission checksHigh: read /etc/shadow, overwrite any file
CAP_SYS_PTRACETrace and inject into other processesHigh: steal secrets from memory, take over root processes
CAP_SETUIDChange UIDs arbitrarilyEquivalent to root
CAP_SYS_ADMINMounts, namespaces, BPF, many device operationsEquivalent to root; often called "the new root"

Each thread has several capability sets. Effective is what the kernel checks; permitted is the ceiling the thread may raise effective to; the bounding set caps what can ever be gained through execve; ambient capabilities survive execve into ordinary binaries, which is how systemd hands a capability to a non-root service. Files can carry capabilities too (setcap), which works like a fine-grained setuid bit.

A service with exactly one capabilityini
# /etc/systemd/system/api.service: bind :443 without being root
[Service]
User=api
Group=api
ExecStart=/usr/local/bin/api --listen :443
AmbientCapabilities=CAP_NET_BIND_SERVICE
CapabilityBoundingSet=CAP_NET_BIND_SERVICE   # cannot gain anything else, even via setuid
NoNewPrivileges=yes                          # execve can never add privilege
UMask=0077
  • `NoNewPrivileges` sets the kernel's no_new_privs flag: after it, execve of a setuid binary or a file with capabilities grants nothing extra. It is inherited by children and cannot be cleared.
  • Containers start with a reduced default set. --cap-drop=ALL --cap-add=NET_BIND_SERVICE is the strict version; --privileged gives all capabilities plus device access and should be treated as running on the host.
  • Inspect: getpcaps <pid>, capsh --decode=<hex> on the CapEff value from /proc/<pid>/status, and getcap -r / 2>/dev/null for file capabilities.

05Least privilege on a real host

▭On the whiteboard · Running a service with least privilege4 points
01
identity
dedicated system user per service | no login shell | no sudo | no docker group
02
files
config root-owned 0640 group=service | secrets 0600 | umask 077 | parent directories not writable by the service
03
privilege
no root | AmbientCapabilities for the one thing it needs | bounding set limited | NoNewPrivileges=yes
04
review
setuid inventory diffed in CI | sudo -l reviewed | group membership audited quarterly
◎Interview radar

A common prompt is "this service runs as root because it listens on port 443; is that a problem?". Strong answers say yes, then give the fix: a dedicated user plus CAP_NET_BIND_SERVICE (or a reverse proxy, or socket activation), NoNewPrivileges, and a bounded capability set. Naming CAP_SYS_ADMIN and the docker group as "root by another name" shows you have seen real escalations.

“How to say it in the room

"I'd run it as its own system user with no shell, give it CAP_NET_BIND_SERVICE through systemd's ambient capabilities, limit the bounding set to that one capability and set NoNewPrivileges so no setuid binary can lift it further. Secrets are mode 0600 owned by that user, and the directories above them are root-owned. Then I'd check the host for the usual escalation paths: unexpected setuid binaries, sudo rules that allow editors or interpreters, and anyone in the docker group."

Test yourself

A user's sudoers entry is `alice ALL=(root) NOPASSWD: /usr/bin/less /var/log/app.log`. Why is this a problem?

Q1Why is a writable directory dangerous even if the files in it are read-only?+

Directory write permission controls creating, deleting and renaming entries. An attacker can delete the protected file and create their own under the same name, unless the sticky bit is set and they do not own the entry.

Q2What is the difference between effective and permitted capabilities?+

Effective is what the kernel checks on each privileged operation. Permitted is the upper limit the process may raise its effective set to. Dropping a capability from permitted is permanent for that process.

Q3Why is `CAP_SYS_ADMIN` treated as equivalent to root?+

It covers mounting filesystems, creating namespaces, loading BPF programs and many device operations. Several of those can be turned into arbitrary code execution as root or into a container escape.

Q4Is a setuid shell script safe?+

Linux ignores the setuid bit on scripts because of the race between the kernel opening the script and the interpreter reading it. Use a small compiled wrapper or, better, a sudo rule or a privileged service with a narrow API.

Finished this one?
Tick it and it shows as done on the roadmap and the course.