# Manage file permissions and ownership

> Read and set rwx permissions with chmod, change owners with chown and chgrp, use SUID, SGID and the sticky bit, and pick a umask.

Source: https://aminbytes.dev/bytes/devices-and-filesystems/permissions-and-ownership/


Linux is a multi-user system from the ground up. Your files, other users' files, programs and even devices all sit in one tree, and **permissions** decide who may read, change or run each of them. Get them too loose and anyone can read your SSH keys. Too tight and your web server can't read its own pages.

Every file has an **owner** (a user), a **group**, and three sets of permissions: one for the owner, one for the group, one for everybody else.

## Reading ls -l

```console
$ ls -l
drwxr-x--- 2 alex devs  4096 Dec  1 10:02 project
-rw-r--r-- 1 alex alex   220 Dec  1 10:00 notes.txt
-rwxr-xr-x 1 root root 14832 Nov 12 08:31 backup.sh
```

Take the first column apart:

```text
-  rw-  r--  r--
│   │    │    └── others (everyone else)
│   │    └─────── group
│   └──────────── user (the owner)
└──────────────── file type
```

The third and fourth columns are the owner and the group.

The first character is the **file type**:

| Char | Type | Example |
| --- | --- | --- |
| `-` | regular file | `/etc/hostname` |
| `d` | directory | `/home` |
| `l` | symbolic link | `/bin` on merged-/usr systems |
| `c` | character device | `/dev/tty`, `/dev/null` |
| `b` | block device | `/dev/sda` |
| `p` | named pipe (FIFO) | made with `mkfifo` |
| `s` | socket | `/run/systemd/notify` |

 (Side note: On RHEL and Fedora you'll often see a dot after the permissions, like `-rw-r--r--.`. It means the file has an SELinux label. A `+` there means the file has extra ACL permissions; `getfacl` shows them.)

## What r, w and x mean

The letters mean slightly different things for files and directories:

| Permission | On a file | On a directory |
| --- | --- | --- |
| `r` read | read the contents | list the names inside (`ls`) |
| `w` write | change the contents | create, delete and rename entries (needs `x` too) |
| `x` execute | run it as a program | enter it (`cd`) and reach files inside |

Two consequences surprise people:

- Deleting a file needs `w` on the **directory**, not on the file. You can delete a read-only file in your own directory.
- A directory with `r` but no `x` lets you see names but not open anything. With `x` but no `r`, you can open a file if you know its exact name, but you can't list them.

**Special files** like devices follow the same rules: permissions decide who may open them. That's why `/dev/sda` is `brw-rw---- root disk`: only root and members of the `disk` group can read the raw disk.

Linux checks the permission sets in order and uses the **first one that matches**: owner, then group, then others. If you own a file with `---rwxrwx`, you can't read it even though everyone else can.

## chmod: changing permissions

`chmod` has two ways to say the same thing.

### Symbolic mode

Who (`u` user, `g` group, `o` others, `a` all), an operator (`+` add, `-` remove, `=` set exactly), and the permissions:

```bash
chmod u+x backup.sh          # owner may run it
chmod go-w notes.txt         # group and others can't write
chmod a=r notes.txt          # everyone read only
chmod u=rwx,g=rx,o= project  # combine with commas
chmod -R g+rX project        # recursive; X = x only on directories
```

The capital `X` adds execute only to directories (and files that are already executable for someone). That's what you want when opening up a whole tree: directories become enterable, but text files don't become "programs".

### Octal mode

Each permission has a number: `r` = 4, `w` = 2, `x` = 1. Add them up per triplet:

| Octal | Symbolic | Typical use |
| --- | --- | --- |
| `644` | `rw-r--r--` | normal files |
| `600` | `rw-------` | private files, SSH keys |
| `755` | `rwxr-xr-x` | programs, normal directories |
| `750` | `rwxr-x---` | directory for owner and group only |
| `700` | `rwx------` | private directory |
| `775` / `664` | `rwxrwxr-x` / `rw-rw-r--` | shared with the group |

```console
$ chmod 640 notes.txt
$ ls -l notes.txt
-rw-r----- 1 alex alex 220 Dec  1 10:00 notes.txt
$ stat -c '%a %A %n' notes.txt
640 -rw-r----- notes.txt
```

`stat -c '%a'` is the quickest way to see a file's mode as a number.

## chown and chgrp: changing ownership

`chown` changes the owner, the group, or both. Only root can give a file to another user:

```bash
sudo chown alex report.pdf          # new owner
sudo chown alex:devs report.pdf     # new owner and group
sudo chown :devs report.pdf         # only the group
sudo chown alex: report.pdf         # owner, and group = alex's login group
sudo chown -R www-data:www-data /var/www/site
```

`chgrp` changes only the group:

```bash
chgrp devs report.pdf
chgrp -R devs project/
```

As a normal user, you can `chgrp` your own files to any group **you are a member of**. Root can use any group.

 (Side note: On older systems you'll also see `chown alex.devs file` with a dot. GNU chown still accepts it, but the colon is the standard form.)

## Sharing with a group

The group field is how you let a team work on the same files. Here two users share `/srv/team`:

```bash
sudo groupadd devs
sudo usermod -aG devs alice
sudo usermod -aG devs bob
sudo mkdir /srv/team
sudo chgrp devs /srv/team
sudo chmod 2770 /srv/team
```

Alice and Bob need to log out and back in (or run `newgrp devs`) before the new group counts. `id` shows which groups you have right now:

```console
$ id
uid=1001(alice) gid=1001(alice) groups=1001(alice),1005(devs)
```

The `2` in `2770` is **SGID** on the directory (next section). It makes every file created inside belong to `devs`, so the whole team can reach it. For them to also *edit* each other's files, those files must be group-writable, which depends on the umask (further down).

## SUID, SGID and the sticky bit

Three special bits sit in front of the normal ones, with their own octal digit:

| Bit | Octal | On a file | On a directory | Shows as |
| --- | --- | --- | --- | --- |
| SUID | `4000` | runs with the **owner's** rights | (ignored) | `s` in the user `x` spot |
| SGID | `2000` | runs with the **group's** rights | new files inherit the directory's group | `s` in the group `x` spot |
| Sticky | `1000` | (ignored on Linux) | only the file's owner may delete or rename it | `t` in the others `x` spot |

You see all three on a normal system:

```console
$ ls -l /usr/bin/passwd
-rwsr-xr-x 1 root root 68248 Mar 23  2023 /usr/bin/passwd
$ ls -l /usr/bin/wall
-rwxr-sr-x 1 root tty 35048 Mar 23  2023 /usr/bin/wall
$ ls -ld /tmp
drwxrwxrwt 14 root root 4096 Dec  1 10:05 /tmp
```

- `passwd` is **SUID root**: when you change your password, it runs as root so it can write `/etc/shadow`.
- `wall` (on Debian/Ubuntu) is **SGID tty**, so it can write to every user's terminal.
- `/tmp` is world-writable with the **sticky bit**: anyone can create files, but you can only delete your own.

Setting them:

```bash
chmod u+s program     # SUID       (or chmod 4755 program)
chmod g+s shared/     # SGID       (or chmod 2775 shared/)
chmod +t public/      # sticky     (or chmod 1777 public/)
```

If the `x` underneath is missing, the letter shows in **capitals**: `S` or `T`. That usually means a mistake, because SUID on a file nobody can run does nothing.

> [!WARNING]
> A SUID-root program runs with full root power, so any bug in it is a security hole. Linux ignores SUID on shell scripts for this reason. Audit them now and then: `find / -perm -4000 -type f 2>/dev/null` lists every SUID file.

## umask: the default permissions

When a program creates a file, it asks for `666` (`rw-rw-rw-`), and for a directory `777`. The **umask** lists the bits to take away from that:

```console
$ umask
0022
$ umask -S
u=rwx,g=rx,o=rx
$ touch a.txt; mkdir dir
$ ls -ld a.txt dir
-rw-r--r-- 1 alex alex    0 Dec  1 10:10 a.txt
drwxr-xr-x 2 alex alex 4096 Dec  1 10:10 dir
```

| umask | New file | New directory | Good for |
| --- | --- | --- | --- |
| `022` | `644` | `755` | the usual default, others can read |
| `002` | `664` | `775` | sharing with your group |
| `027` | `640` | `750` | nothing for others |
| `077` | `600` | `700` | fully private |

The umask **removes** bits, it doesn't subtract numbers. With umask `033`, a file gets `644`, not `633`, because there was no `x` to remove in the first place. And a new file never gets `x` from the umask: you always add that yourself with `chmod`.

Change it for the current shell with `umask 027`. It only lasts for that shell and its children, so to keep it, put the line in `~/.bashrc` (just you) or a file under `/etc/profile.d/` (everyone). The system default is also set by `UMASK` in `/etc/login.defs`.

Root usually gets `0022`. Many distributions give normal users `0002` when each user has a private group of the same name (Ubuntu does, and so do RHEL and Fedora), because then group-writable is safe.

## Exam checklist

- `ls -l` first character: `-` file, `d` dir, `l` link, `c`/`b` char/block device, `p` pipe, `s` socket.
- `r`=4, `w`=2, `x`=1. On a directory, `w` means create/delete entries, `x` means enter it. Deleting needs `w` on the directory.
- `chmod` symbolic (`u g o a`, `+ - =`) or octal (`755`, `644`). `-R` is recursive, `X` sets `x` only on directories.
- `chown user:group file`, `chown :group file`, `chgrp group file`. Only root can change the owner.
- SUID `4000` (`s` in user), SGID `2000` (`s` in group), sticky `1000` (`t` in others). Capital `S`/`T` = bit set but no `x`.
- SGID on a directory: new files inherit its group. Sticky on a directory: only the owner can delete (like `/tmp`, mode `1777`).
- umask removes bits from `666` (files) and `777` (directories): `022` gives `644`/`755`, `027` gives `640`/`750`.
- `umask` is per shell: set it in `~/.bashrc`, `/etc/profile` or `/etc/login.defs` to make it stick.


## Byte check

1. Your umask is `027`. What permissions does a new **file** get, and a new **directory**?
   - **File `640`, directory `750`** (correct)
   - File `751`, directory `750`
   - File `027`, directory `027`
   Files start from `666` and directories from `777`, and the umask takes bits away: removing `027` from `666` leaves `640`, from `777` it leaves `750`.

2. `/srv/team` is `drwxrws--- root devs`. Alice creates `plan.txt` in it. Which group owns the new file?
   - Alice's primary group
   - **`devs`** (correct)
   - `root`
   The `s` in the group triplet is SGID. On a directory, it makes new files inherit the directory's group instead of the creator's primary group.

3. Everyone can write to `/tmp`, so why can't Bob delete Alice's files there?
   - Files in `/tmp` are read-only
   - `/tmp` has SUID set
   - **`/tmp` has the sticky bit (`t`): only a file's owner, the directory's owner or root may delete it** (correct)
   Without the sticky bit, write permission on a directory lets you delete any file in it. `drwxrwxrwt` (mode `1777`) stops that.


