toolhq.io

All posts
4 min readby Jameel Haider

setuid, setgid, and the sticky bit explained

Most people learn Unix permissions as three digits, like 755, and never meet the fourth one that sometimes appears in front, as in 4755. That leading digit controls three special bits that change who a program runs as and who may delete files in a shared directory. They are worth understanding because they affect security directly.

The fourth digit

A full permission value has four octal digits. The last three are the familiar owner, group, and other bits. The first digit holds three special bits, each with its own value:

  • setuid is 4
  • setgid is 2
  • sticky is 1

So 4755 sets setuid on top of 755, and 1777 sets the sticky bit on top of 777. You add the values the same way you add read, write, and execute.

setuid and setgid run as the owner

Normally a program runs with your identity. When a file has the setuid bit, it instead runs as the file's owner, no matter who launches it. The classic example is passwd, owned by root, which needs to edit /etc/shadow. A regular user runs it, but it executes with root's authority for the duration.

setgid does the same for the group. On a directory it behaves differently and more usefully: new files created inside inherit the directory's group rather than the creator's primary group. That is how a shared project directory keeps every file under one team group automatically.

Because setuid grants another identity, a setuid-root binary with a bug is a privilege escalation path. Set it only on programs that genuinely need it.

The sticky bit protects shared directories

On a directory, the sticky bit means only the owner of a file may rename or delete it, even if other users have write access to the directory. The canonical case is /tmp: everyone can create files there, but you cannot delete someone else's. Without the sticky bit, write access to a directory lets you remove any file in it.

drwxrwxrwt  18 root root 4096 Oct  2 09:14 /tmp

Reading them in ls

The special bits replace the execute character in the ls -l output:

  • s in the owner slot means setuid (rwsr-xr-x).
  • s in the group slot means setgid.
  • t in the other slot means sticky (rwxrwxrwt).

A capital S or T means the bit is set but the underlying execute bit is not, which is usually a mistake worth checking.

You can compute any of these without memorizing the octal math. The chmod calculator lets you toggle each special bit and shows the resulting number and symbolic string side by side, and it runs entirely in your browser so nothing you type is sent anywhere. If the plain three-digit model is still fuzzy, start with understanding chmod and Unix permissions, then come back for the fourth digit.

In practice you will set the sticky bit on shared upload directories and setgid on team folders far more often than you will ever touch setuid. Treat setuid as something you audit rather than something you add casually.