Thursday, May 17, 2012

HOWTO use the Sticky Bit on a directory or file

The main property about the Sticky Bit on directories is that other users cannot delete or rename the files (or subdirectories) within that directory. When the sticky bit is set on a directory, only the owner and the root user can delete / rename the files or directories within that directory.

1. Set the Sticky bit on directory


Use chmod command to set the sticky bit. If you are using the octal numbers in chmod, give 1 before you specify other numbered privileges, as shown below. The example below, gives rwx permission to user, group and others (and also adds the sticky bit to the directory).

ximena@anakin:# chmod 1777 dir

Or, you can assign only sticky bit to an existing directory (without touching any other user, group and other privileges) using chmod command as shown below.

ximena@anakin:# chmod +t dir

Once the sticky bit is assigned to a directory, you’ll see (t) as the last character in the permission. In this example, it is drwxrwxrwt.

ximena@anakin:# ls -ld /home/ximena/dir
drwxrwxrwt 2 ximena ximena 4096 2012-05-17 14:09 /home/ximena/dir
ximena@anakin:# ls -l dir
total 8
-rwxrwxrwx 1 ximena ximena   20  2012-05-17 14:12 ximunix.txt
-rwxrwxrwx 1 guest guest 41  2012-05-17 14:13 guest.txt

In the above example, as dir has rwx permission to everybody, all other users are allowed to do create their files or directories under this directory. However, even when the sub-directories or files under dir is having rwx permission to everybody, only the owner of those can delete or rename those files and directory. Other users cannot delete or rename it because of sticky bit.

In the above example, ximunix.txt has rwx to users, groups, and others. But, when guest user is trying to delete the file bala.txt, he’ll see the “Operation not permitted” message as shown below.

ximena@anakin:# su guest
Password:
ximena@anakin:# cd /home/bala/dir1
ximena@anakin:# rm bala.txt
rm: cannot remove `bala.txt': Operation not permitted

Please note that /tmp has sticky bit enabled by default. You might have not noticed that until now. Now you know why /tmp directory is supposed to have sticky bit enabled.

ximena@anakin:# ls -ld /tmp
drwxrwxrwt 3 root root 4096 Jan 31 08:29 /tmp

To remove the sticky bit from a directory, do the following.

ximena@anakin:# chmod -t dir

2. Set the sticky bit on File

Setting the sticky bit on a file is pretty much useless, and it doesn’t do anything. On some of the older *nix flavors, a sticky bit enabled executable file will be loaded to the swap memory after 1st execution, which speeds up all subsequent execution. This is not true anymore.