Sticky folders on Linux

2016-11-22 - A quick guide how to set sticky bit on Linux to propagate user and group ownership to directory content

Every once in a while when developing something on Linux, I am facing the similar issues. The question is how to ensure that all files in a directory, regardless of who is creating them, are accessible by multiple users.

Obvious solution is to just assign ownership of the files to some group, and give permissions to that group. Then, all users that are members of that group can access them.

This works fine, until one of the users creates a new file, or a new directory. In that case, he is the owner of that one file or directory, and access by other users depend on his default settings. Obviously, root can fix that by running chown and changing ownership again, but that's a manual process.

Luckily, since we are running Linux, the solution exists:

# First change ownership of the current directory
chown -R user_1:group_1 ./somedir

# Set file ACL for the directory
setfacl -Rdm u::rwx,g::rwx ./somedir

From now on, every file and directory created in somedir will inherit group1 as the primary group, thus be accessible to all group members.

Now, we only need to make sure all files are accessible to that group, and none else.

# All files should be readable and writeable only to owner and group
find ./somedir -type f -exec chmod 660 {} + -o -type d -exec chmod 2770 {} +

# All executables should also be executable by all group members
find ./somedir -name "*.sh" -exec chmod 770 {} +

And that's basically it.

One of the common use cases would be when we have multiple users working on the same application. Then we can create a group and user for the project, set the ownership to the project directory to that group, and add all project members to the group. Then, they all can access the files there, as well as the application user running the application, without danger that they will create a file that application user doesn't have permission to read.

Keywords: linux security