Linux Users, Groups, Permissions, sudo and SUID
A small company runs a nightly backup as root from cron: /opt/backup/run.sh. Years ago someone made the script writable by everyone "so the developers can tweak the paths". Any local user, or any web application running as www-data that an attacker has taken over, can now append one line to that script and wait for midnight: the line runs as root. Nothing was hacked in the usual sense. A permission bit was wrong, and the system did exactly what the bits said.
Most Linux privilege problems look like this. The kernel's access rules are simple and strict; the mistakes are in how people set them. This lesson reads the rules with an auditor's eyes: which settings are dangerous, how to find them, and how to fix them. The mechanics themselves (how the kernel compares UIDs and bits) are in Linux Users & Permissions; the commands are in Bash: Permissions and Bash: Users & Groups.
The model in one table
Every file has an owner (a UID), a group (a GID) and permission bits. Every process runs with a UID and a set of GIDs. The kernel checks the first class that applies: owner, else group, else other.
| Bit | On a file | On a directory | Why an auditor cares |
|---|---|---|---|
r |
read the content | list the names | secrets readable by everyone (o+r on a key or .env) |
w |
change the content | create, delete, rename entries | world-writable scripts, configs and directories in a root PATH |
x |
execute | enter (cd), reach entries by name |
|
SUID (s in the owner x place, octal 4000) |
the program runs with the file owner's UID | (ignored) | every SUID-root program is code that a normal user can run as root |
SGID (s in the group place, 2000) |
runs with the file's GID | new files inherit the directory's group | shared project directories |
sticky (t in the other place, 1000) |
(ignored) | only the owner of an entry may delete or rename it | /tmp without it lets users delete each other's files |
On top of the bits, sudo lets chosen users run chosen commands as another user (usually root), according to /etc/sudoers and /etc/sudoers.d/. It is the deliberate, logged way to grant privilege; SUID is the old, silent one.
Reading permissions as an auditor
The session below runs in your sandbox as the unprivileged user learner, on files it creates itself. stat -c prints the symbolic mode, the octal mode, owner and group, which is easier to compare than ls -l.
umask
mkdir -p demo/app demo/shared
echo 'DB_PASSWORD=lab-only' > demo/app/.env
echo 'echo backing up' > demo/app/run.sh
chmod 755 demo/app/run.sh
chmod 777 demo/shared
chmod 666 demo/app/.env
stat -c '%A %a %U:%G %n' demo/app/.env demo/app/run.sh demo/shared /tmp
echo '--- fixed'
chmod 600 demo/app/.env
chmod 1770 demo/shared
stat -c '%A %a %U:%G %n' demo/app/.env demo/shared0022
-rw-rw-rw- 666 learner:learner demo/app/.env
-rwxr-xr-x 755 learner:learner demo/app/run.sh
drwxrwxrwx 777 learner:learner demo/shared
drwxrwxrwt 1777 root:root /tmp
--- fixed
-rw------- 600 learner:learner demo/app/.env
drwxrwx--T 1770 learner:learner demo/shared
Three things to notice. The default umask 0022 means new files are 644 and new directories 755: readable by everyone, which is wrong for secrets. /tmp is 1777: world-writable but sticky, so users can't delete each other's files. And the fixed shared directory shows a capital T: the sticky bit is set but "other" has no x, which is how ls marks that combination.
Finding the dangerous settings
An audit is a set of find queries. Each one answers "who besides the owner can change or abuse this?". Here they run over the whole sandbox image; -xdev stays on one file system and 2>/dev/null hides directories learner may not read.
echo '== SUID and SGID programs'
find / -xdev -type f \( -perm -4000 -o -perm -2000 \) 2>/dev/null | sort | xargs stat -c '%A %U %n'
echo '== world-writable files outside /proc, /sys and /tmp'
find / -xdev -type f -perm -0002 ! -path '/proc/*' ! -path '/sys/*' ! -path '/tmp/*' 2>/dev/null | wc -l
echo '== world-writable directories without the sticky bit'
find / -xdev -type d -perm -0002 ! -perm -1000 2>/dev/null | wc -l
echo '== files with no known owner'
find / -xdev \( -nouser -o -nogroup \) 2>/dev/null | wc -l== SUID and SGID programs
-rwxr-sr-x root /usr/bin/chage
-rwsr-xr-x root /usr/bin/chfn
-rwsr-xr-x root /usr/bin/chsh
-rwxr-sr-x root /usr/bin/expiry
-rwsr-xr-x root /usr/bin/gpasswd
-rwsr-xr-x root /usr/bin/mount
-rwsr-xr-x root /usr/bin/newgrp
-rwsr-xr-x root /usr/bin/passwd
-rwsr-xr-x root /usr/bin/su
-rwsr-xr-x root /usr/bin/umount
-rwxr-sr-x root /usr/sbin/pam_extrausers_chkpwd
-rwxr-sr-x root /usr/sbin/unix_chkpwd
== world-writable files outside /proc, /sys and /tmp
0
== world-writable directories without the sticky bit
0
== files with no known owner
0
This is a clean image: eight SUID-root programs that need it (passwd must write /etc/shadow, su and mount must switch identity), four SGID programs (rwxr-sr-x: chage, expiry, unix_chkpwd and pam_extrausers_chkpwd run with the shadow group so they can read password data) and nothing world-writable. On a real server you keep the SUID list as a baseline and alert on any change, because a new SUID-root binary is one of the classic signs that someone has already become root and left themselves a way back (see Privilege Escalation).
sudo: deliberate privilege, easy to over-grant
A sudo rule reads who host = (as whom) what. The syntax is covered in sudo & sudoers. From a security point of view, three patterns turn a narrow rule into full root:
ALLas the command, especially withNOPASSWD:: the account is root, and so is anyone who steals its session.- A program that can run other programs: editors (
vim,less,nanocan open a shell or write any file), interpreters (python3,perl,bash),find -exec,tarwith its checkpoint actions, package managers. Grantingsudo vim /etc/hostsgrants everything vim can do as root. - Wildcards and writable targets:
/usr/bin/systemctl restart *, or a script in a directory the user can write.
The checker below reads a lab sudoers file (a string in the example; on a host you would read /etc/sudoers and /etc/sudoers.d/* as root) and flags those patterns.
SUDOERS = """\
Defaults use_pty, logfile="/var/log/sudo.log"
%admins ALL=(ALL:ALL) ALL
deploy ALL=(root) NOPASSWD: /usr/bin/systemctl restart lab-app.service
backup ALL=(root) NOPASSWD: /usr/bin/tar
alice ALL=(root) /usr/bin/vim /etc/hosts
ci ALL=(ALL) NOPASSWD: ALL
web ALL=(root) NOPASSWD: /usr/bin/systemctl restart *
"""
SHELL_CAPABLE = {"vim", "vi", "nano", "less", "more", "python3", "perl", "bash", "sh",
"find", "tar", "awk", "env", "apt", "pip"}
for line in SUDOERS.splitlines():
if not line.strip() or line.startswith("Defaults"):
continue
who, rest = line.split(None, 1)
cmds = rest.split(")", 1)[1].replace("NOPASSWD:", "").strip()
issues = []
if cmds == "ALL":
issues.append("full root")
if "NOPASSWD" in rest:
issues.append("no password")
prog = cmds.split()[0].rsplit("/", 1)[-1]
if prog in SHELL_CAPABLE:
issues.append(f"{prog} can start a shell")
if "*" in cmds:
issues.append("wildcard")
print(f"{who:8} {', '.join(issues) if issues else 'ok'}")%admins full root
deploy no password
backup no password, tar can start a shell
alice vim can start a shell
ci full root, no password
web no password, wildcard
The checker is deliberately blunt: %admins with a password is "full root" by design, a normal policy for people on call, and a reviewer accepts it as such; ci with NOPASSWD: ALL makes the CI runner's credentials root credentials. deploy shows the safe shape: one exact command, one exact unit.
How it is detected
- Baselines: record the SUID/SGID list, world-writable paths and sudoers files (with their hashes) and compare every day. File-integrity tools (AIDE, or a Linux audit rule) alert on changes to
/etc/sudoers*,/etc/passwd,/etc/shadow. - sudo logs: every use is logged (
sudo: alice : TTY=pts/0 ; PWD=/home/alice ; USER=root ; COMMAND=/usr/bin/vim /etc/hostsin the auth log or journal). A burst of failures or an unusual command for an account is a signal. - New accounts and group changes:
useradd,usermod -aG sudolines in the auth log; a second UID 0 account in/etc/passwd(awk -F: '$3 == 0' /etc/passwdshould print onlyroot).
How it is fixed or prevented
- Secrets
600(or640with a dedicated group), never world-readable; setUMask=0027for services andumask 027for admin shells. - Scripts that root runs are owned by root and writable only by root, and so is every directory above them and every directory in root's
PATH. - Remove SUID from anything that doesn't need it (
chmod u-s), mount data and upload partitions withnosuid,nodev,noexec, and prefer capabilities (setcap cap_net_bind_service+ep) to SUID root for programs that need one privilege. - sudo rules: exact commands with full paths, no editors or interpreters (use
sudoeditfor editing files), no wildcards,NOPASSWDonly for automation with one narrow command, always edited withvisudo. - Run services under their own unprivileged account (service accounts).
Pitfalls
- Group write is not harmless.
775on a root-run script lets the whole group become root. - The parent directory matters. A
644root-owned script inside a directory writable by others can be deleted and replaced. chmod -R 777"to fix it" is the most common cause of these findings. Find out which user needs which access instead.- ACLs hide permissions. A
+after the mode inls -lmeans extra entries; check them withgetfacl.
Practice
- A file shows
-rwsr-xr-x root root /usr/local/bin/report. What does that mean, and what would you check? - Which octal mode would you give a directory where the
devsgroup shares files but nobody may delete another's files? - Rewrite the
backupsudo rule from the example so it can only create one archive of/srv/data.
Answers
- It is SUID root: any user who runs it runs it as root. Check who installed it and when (package manager:
dpkg -S), whether it is in your baseline, whether it can run other programs or read user-chosen files, and whether it needs SUID at all. 3770with groupdevs: SGID (2000) so new files belong todevs, sticky (1000) so only owners delete,rwxfor owner and group, nothing for others.- Point it at a root-owned wrapper with no arguments, for example
backup ALL=(root) NOPASSWD: /usr/local/sbin/backup-srv-data, where the script runs a fixedtar -czf /var/backups/srv-data.tgz /srv/data.taritself can run commands through--checkpoint-action, so it must never be granted with free arguments.
Test yourself
What does the SUID bit on a root-owned executable do?
- Only root may run it
- Anyone who runs it runs it with root's UID
- It cannot be deleted
- It runs in a sandbox
Why is /tmp mode 1777 and not 0777?
- 1 makes it faster
- The sticky bit stops users deleting or renaming each other's files
- It makes the directory read-only
- It hides the directory
Which sudo rule is the safest?
alice ALL=(root) /usr/bin/vim /etc/hostsci ALL=(ALL) NOPASSWD: ALLdeploy ALL=(root) NOPASSWD: /usr/bin/systemctl restart lab-app.serviceweb ALL=(root) NOPASSWD: /usr/bin/systemctl restart *
A daily job reports a new SUID-root file in /var/tmp. What is the best first reaction?
- Ignore it, SUID files are normal
- Treat it as a possible compromise: preserve evidence and investigate who created it
- Run it to see what it does
- Delete
/var/tmp