ubuntu, updated
How permissions work
Read rwx and octal permissions, change them with chmod and chown, and fix the classic Permission denied error.
Reading ls -l
-rw-r----- 1 anna developers 4096 Oct 21 08:00 report.txt
│└┬┘└┬┘└┬┘ └─┬┘ └───┬────┘
│ │ │ │ │ └ group
│ │ │ │ └ owner (user)
│ │ │ └ others: --- nothing
│ │ └ group: r-- read
│ └ owner: rw- read + write
└ type: - file, d directory, l link
Every file has one owner, one group and three permission sets: for the owner (u), the group (g) and everyone else (o). Linux checks them in that order and uses the first one that matches.
What r, w, x mean
| On a file | On a directory | |
|---|---|---|
| r (4) | Read the content | List the names inside (ls) |
| w (2) | Change the content | Create, delete, rename files inside |
| x (1) | Run it as a program | Enter it (cd) and access files inside |
Note: deleting a file needs w on the directory, not on the file.
Octal numbers
Add up r=4, w=2, x=1 for each of user, group, others:
| Number | Means | Typical for |
|---|---|---|
644 | rw-r—r— | Normal files |
640 | rw-r----- | Config files with secrets, group may read |
600 | rw------- | Private keys, passwords |
755 | rwxr-xr-x | Directories, scripts, programs |
750 | rwxr-x--- | Directories only the group may enter |
700 | rwx------ | Private directories (~/.ssh) |
777 | rwxrwxrwx | Never. It is not a fix, it’s a hole. |
chmod and chown cheat sheet
| What | Command |
|---|---|
| Set exact permissions | chmod 640 file |
| Add execute for the owner | chmod u+x script.sh |
| Remove all rights for others | chmod o-rwx file |
| Give the group the same as the owner | chmod g=u file |
| Change owner | sudo chown anna file |
| Change owner and group | sudo chown anna:developers file |
| Change only the group | sudo chgrp developers file |
| Recursively | add -R, e.g. sudo chown -R anna:developers /srv/app |
| Dirs 755, files 644, recursively | sudo chmod -R u=rwX,go=rX /srv/app |
The capital X sets execute only on directories (and files that are already executable). That’s the clean way to fix a whole tree.
“Permission denied”: checklist
- Who am I?
id - Who owns it and what are the rights?
ls -l file - Check every folder on the path, each needs
x:namei -l /srv/app/conf/app.yml - Just added to a group? Log out and in again.
- Still denied with fitting rights? Check ACLs (
getfacl file, see Special permissions and ACLs) and AppArmor (sudo dmesg | grep -i apparmor).