Linux permissions are pretty straightforward once you understand them. The permissions are read, write and execute. Read means you have access to view a file or directory, think cat, ls or using a program like LibreOffice Writer. Write permissions allow you to make changes to files and directories, as in write them to the disk. Finally there’s execute, running a script for example.
The issue comes in when you want a person to have the ability to make changes, write, but not delete a file. This happened to me recently when I added a feature to a python script that writes variables to a log file. I didn’t want to accidentally delete the file, but I didn’t want to run the script with elevated privileges either.
If you’ve ever seen file permissions in Linux, it usually looks something like this: -rwxrw-rw-
And a directory would look similar, but with a d at the beginning: drwxr-xr-x
When a sticky bit is added, it has a T at the end: -rwx-rw-rwT
A sticky bit is a slight deviation from the normal way Linux permissions operate. When a sticky bit is assigned, to delete the file, a user must be the owner. Some ways this can resolve the issue I had are to change the ownership of the file to root, or to create a new system user, who would own the file.
The system account we are going to create is similar to the ones created during installation. They are setup differently than standard user accounts as no one is meant to login to them. The account won’t have a password or a home directory. We are going to use the -r flag to specify this is a system account.
sudo useradd -r accountName
Now if you check the /etc/passwd file you can find the user we’ve created.
If you go over to the /etc/shadow file you’ll see there’s no password hash stored here.
Now that we’ve created a new user, we’ll change the ownership of the file to this new user.
To do this we’ll use the chown command.
Sudo chown accountName:accountName fileName
Next we’ll add the sticky bit using chmod. For the test file I’m creating for this blog, I want other users to be able to write to the file, but not delete it. For the purposes of this post, I’m going to give all users read and write permissions. Assign the permissions appropriate for your circumstances. The 1 before the rest of the permissions is what adds a sticky bit. There are other ways to add a sticky bit, but I’m going to display the numeric method.
sudo chmod 1666 fileName
You can verify the sticky bit was added by using -l flag with ls.
ls -l fileName
Now if you attempt to delete the file as someone other than the owner, you should get an “rm: cannot remove ‘fileName’: Operation not permitted” message.