File permissions: chmod and chown

Linux · Essentials · 12 min

Permission errors are the most common Linux problem, and wrong permissions are a common security hole.

Every file has an owner, a group and three permission sets: for the user (owner), the group and others. ls -l shows them as a string like -rwxr-x---: the first character is the type (- file, d directory, l symlink), then three rwx triplets.

For files, r allows reading, w writing and x executing. For directories the meaning differs: r lists the names, w creates, deletes and renames entries, and x allows entering and accessing items inside. A directory usually needs r and x together.

chmod changes permissions in two notations:

  • symbolic: chmod u+x script.sh, chmod go-w file, chmod u=rw,g=r,o= file,
  • octal: each triplet is a digit with r=4, w=2, x=1, so chmod 644 is rw-r--r--, 755 rwxr-xr-x, 600 rw-------, 750 rwxr-x---.

chown user:group file changes ownership (root only); chown -R recurses, and chgrp changes just the group. Use -R with care: making a whole tree executable or world-writable is a classic mistake.

Typical settings: scripts 755, private keys 600 (SSH refuses keys that are too open), config with secrets 640 owned by root and the service's group, web content readable but not writable by the web server user.

Example

cd "$(mktemp -d)"
touch script.sh notes.txt
ls -l script.sh                  # -rw-r--r-- 1 ada ada 0 ... script.sh
chmod +x script.sh               # add execute (filtered by your umask)
chmod u=rwx,g=rx,o= script.sh
stat -c '%A %a %n' script.sh     # -rwxr-x--- 750 script.sh
chmod 640 notes.txt
stat -c '%A %a %n' notes.txt     # -rw-r----- 640 notes.txt
mkdir shared && chmod 750 shared # dirs: x = may enter, r = may list
stat -c '%A %a %n' shared        # drwxr-x--- 750 shared
# sudo chown ada:developers notes.txt     # owner and group
# sudo chown -R www-data: /var/www/site   # recursive; "user:" = user's login group

Remember

  • rwx for user, group, others; octal r=4 w=2 x=1
  • On directories x means enter, r means list, w means create/delete
  • chown user:group changes ownership; be careful with -R

Watch out for

  • Fixing a permission error with chmod 777, which lets every user modify the file.

Check yourself

  1. What does chmod 640 give a file?
  2. A user can list a directory's names but gets 'Permission denied' opening any file inside. Which bit is missing on the directory?

Sign in to answer, see the explanations, and get this lesson back as a quick review later.

Official docs: man7.org/linux/man-pages/man1/chmod.1.html