TExcelTAD
Home › Operating Systems: Linux & Windows › Linux Users & Permissions

Linux Users & Permissions

Linux was designed from the start as a multi-user system: many people, and many services, share one kernel, and none of them may read another's private files or kill another's processes. The kernel enforces this with a model that is simple at its core (users, groups and nine permission bits) and has grown several extra layers (capabilities, ACLs, SELinux/AppArmor, seccomp, namespaces). This lesson explains how the kernel actually makes its decisions. For the day-to-day commands, see Bash: Permissions and Bash: Users & Groups.

Identities are numbers

To the kernel, a user is a UID and a group is a GID, nothing more. Every process carries the UID and GIDs of whoever started it, and every inode stores one owner UID and one group GID. The names come from text files that user-space tools look up:

File One line per Fields
/etc/passwd user name, x, UID, primary GID, comment, home, shell
/etc/shadow user name, password hash, ageing data (root only)
/etc/group group name, x, GID, member list
bash · try it yourself
id
getent passwd root learner nobody
getent group learner
cat /etc/shadow 2>&1
uid=1000(learner) gid=1000(learner) groups=1000(learner)
root:x:0:0:root:/root:/bin/sh
learner:x:1000:1000:learner:/home/learner:/bin/bash
nobody:x:65534:65534:nobody:/:/sbin/nologin
learner:x:1000:
cat: /etc/shadow: Permission denied

Three ranges matter:

UID Who Example
0 root, the superuser: the kernel skips most permission checks root
1–999 system users for services, no login shell www-data, postgres, systemd-network
1000+ human users ada, learner

Running each service under its own system user is the cheapest security measure Linux has: a hacked web server running as www-data cannot read postgres's files.

How the kernel checks a file access

When a process opens a file, the kernel compares the process's identity with the file's owner, group and mode bits. The important detail is that exactly one of the three classes applies, chosen in order: owner, then group, then others. The program below implements that algorithm:

python · try it yourself
def classes(mode):                          # 0o640 -> ('rw-', 'r--', '---')
    bits = "rwx"
    return tuple("".join(b if mode >> (6 - 3 * c) & (4 >> i) else "-" for i, b in enumerate(bits))
                 for c in range(3))

def may(proc, f, want):                     # want is "r", "w" or "x"
    if proc["uid"] == 0:
        if want != "x" or "x" in "".join(classes(f["mode"])):
            return "allowed (root bypasses the check)"
    owner, group, other = classes(f["mode"])
    if proc["uid"] == f["uid"]:
        cls, perms = "owner", owner
    elif f["gid"] in proc["groups"]:
        cls, perms = "group", group
    else:
        cls, perms = "other", other
    verdict = "allowed" if want in perms else "DENIED"
    return f"{verdict} (as {cls}: {perms})"

report = {"uid": 1000, "gid": 1000, "mode": 0o640}      # -rw-r----- ada:ada
weird  = {"uid": 1000, "gid": 1000, "mode": 0o466}      # -r--rw-rw- ada:ada

ada   = {"uid": 1000, "groups": {1000}}
bob   = {"uid": 1001, "groups": {1001, 1000}}           # bob is in ada's group
eve   = {"uid": 1002, "groups": {1002}}
root  = {"uid": 0,    "groups": {0}}

for who, p in [("ada", ada), ("bob", bob), ("eve", eve), ("root", root)]:
    print(f"{who:4} read  report: {may(p, report, 'r')}")
print(f"bob  write report: {may(bob, report, 'w')}")
print(f"ada  write weird : {may(ada, weird, 'w')}")
print(f"bob  write weird : {may(bob, weird, 'w')}")
ada  read  report: allowed (as owner: rw-)
bob  read  report: allowed (as group: r--)
eve  read  report: DENIED (as other: ---)
root read  report: allowed (root bypasses the check)
bob  write report: DENIED (as group: r--)
ada  write weird : DENIED (as owner: r--)
bob  write weird : allowed (as group: rw-)

The last two lines are the surprising part: on -r--rw-rw-, the owner is the only person who may not write, because the kernel never falls through to the group or other bits once the owner class matched. (Ada can still chmod her own file, so it is no real protection, but it shows the rule.)

On directories the bits mean something else: r lists names, w creates/deletes/renames entries, and x lets you pass through the directory to reach anything inside. That is why deleting a file depends on the directory's w, not on the file's own permissions.

umask: the default permissions

New files start from mode 666 (directories 777) and the process's umask removes bits from that. The usual umask 022 takes write away from group and others; a stricter 077 makes new files private:

bash · try it yourself
umask
touch default.txt
umask 077
touch private.txt
umask 022
stat -c '%A %a %n' default.txt private.txt
chmod u=rwx,g=rx,o= default.txt
stat -c '%A %a %n' default.txt
0022
-rw-r--r-- 644 default.txt
-rw------- 600 private.txt
-rwxr-x--- 750 default.txt

Special bits: setuid, setgid, sticky

Bit On a file On a directory Shown as
setuid (4000) The program runs with the file owner's UID — s in the owner's x place
setgid (2000) Runs with the file's group New files inherit the directory's group s in the group's x place
sticky (1000) — Only a file's owner may delete it (/tmp) t in the others' x place

passwd must write /etc/shadow, which ordinary users cannot even read. It is therefore setuid root: whoever runs it gets the effective UID 0 for that process only, and the program itself makes sure you can change only your own password. These are the setuid programs in the sandbox:

bash · try it yourself
find / -xdev -perm -4000 -type f 2>/dev/null | sort | xargs stat -c '%A %U %n'
stat -c '%A %n' /tmp
-rwsr-xr-x root /bin/mount
-rwsr-xr-x root /bin/umount
-rwsr-xr-x root /usr/bin/chage
-rwsr-xr-x root /usr/bin/chfn
-rwsr-xr-x root /usr/bin/chsh
-rwsr-xr-x root /usr/bin/expiry
-rwsr-xr-x root /usr/bin/gpasswd
-rwsr-xr-x root /usr/bin/passwd
drwxrwxrwt /tmp

Every setuid-root program is a potential way to become root if it has a bug, so security audits start with exactly this find command.

root, sudo and capabilities

Traditionally there were two kinds of process: UID 0, which may do anything, and everyone else. Modern Linux splits root's power into about 40 capabilities, each covering one privileged operation, and a process can hold just the ones it needs:

Capability Allows
CAP_NET_BIND_SERVICE Listening on ports below 1024
CAP_NET_ADMIN Configuring interfaces, routes, firewall
CAP_SYS_ADMIN A huge grab-bag: mount, many ioctls (the "new root")
CAP_DAC_OVERRIDE Ignoring file permission bits
CAP_CHOWN Changing file owners
CAP_KILL Sending signals to other users' processes
CAP_SYS_MODULE Loading kernel modules

/proc/self/status shows the capability sets as bit masks. As the normal user learner, the effective set is empty:

bash · try it yourself
grep -E '^Cap(Prm|Eff)' /proc/self/status
CapPrm:	0000000000000000
CapEff:	0000000000000000

Humans get root powers through sudo, which checks /etc/sudoers (usually "members of group sudo or wheel may run anything after typing their own password") and logs every command (sample session):

bash
ada@ubuntu:~$ sudo -l
User ada may run the following commands on ubuntu:
    (ALL : ALL) ALL
ada@ubuntu:~$ sudo id -u
[sudo] password for ada:
0
ada@ubuntu:~$ sudo setcap cap_net_bind_service=+ep /opt/notely/bin/server
ada@ubuntu:~$ getcap /opt/notely/bin/server
/opt/notely/bin/server cap_net_bind_service=ep

After that setcap, the web server can listen on port 80 without running as root at all.

The extra layers

Layer What it adds Commands
POSIX ACLs Permissions for extra named users/groups on one file getfacl, setfacl -m u:bob:rw file
SELinux (Fedora, RHEL) Mandatory access control: every process and file has a label; a policy says which labels may interact, even for root getenforce, ls -Z, restorecon
AppArmor (Ubuntu, Debian, SUSE) Mandatory access control by path-based per-program profiles aa-status, /etc/apparmor.d/
seccomp A filter on which system calls a process may make used by Docker, systemd, Chrome
Namespaces + cgroups Separate views of PIDs, mounts, network, users; resource limits the basis of containers (Virtualization & Containers)

The sandbox itself is protected by two of them, which you can see from inside:

bash · try it yourself
grep -E '^(Seccomp|NoNewPrivs):' /proc/self/status
ls /proc/self/ns | tr '\n' ' '; echo
NoNewPrivs:	0
Seccomp:	2
cgroup ipc mnt net pid pid_for_children time time_for_children user uts

Seccomp: 2 means a system-call filter is active (Docker's default profile blocks around 40 dangerous calls such as reboot and kexec_load), and the ns entries are the namespaces that give the container its own process list, mounts, hostname and network.

Compared with Windows

Concept Linux Windows (Windows Users, UAC & ACLs)
Identity UID / GID numbers SIDs (S-1-5-21-…-1001)
Superuser root (UID 0) Administrators group + SYSTEM account
Becoming admin sudo UAC elevation prompt
File permissions Owner/group/other bits (+ ACLs) ACLs with many rights and inheritance
Fine-grained privileges Capabilities Privileges (SeBackupPrivilege, SeDebugPrivilege)
Mandatory control SELinux / AppArmor Integrity levels (Low, Medium, High, System)

Learn more: Bash: Permissions · Bash: Users & Groups · Windows Users, UAC & ACLs

Go further: Linux Users, Groups, Permissions, sudo and SUID reads permissions as an auditor and finds the dangerous settings.

Test yourself

Bob is in the file's group but not its owner. The file is -rw----r--. Can Bob read it?

  1. Yes, others have read
  2. No: the group class matched and it grants nothing
  3. Yes, because he is in the group
  4. Only with sudo

Why is /usr/bin/passwd setuid root?

  1. So only root can run it
  2. So any user can update their own entry in /etc/shadow, which only root may write
  3. To make it run faster
  4. It is a security bug

What is the advantage of setcap cap_net_bind_service=+ep over running a web server as root?

  1. None, it is the same
  2. The server gets only the right to bind low ports, not all of root's powers
  3. It encrypts the traffic
  4. It makes the server setuid