Linux file permissions can be confusing for those new to it. The entire idea of file permissions rests on owners and groups. We can use the chmod command to give permissions to the owner, or any group. But what if these aren’t granular enough? What if you need to provide specific file permissions to a user?
The Traditional Linux Approach
The regular ways to manage specific user rights to a file are:
- Create a new and separate group for that user;
- Make that user the owner of the file and manage permissions apart.
However, both solutions can be overkill. The second one can mess what you’re trying to achieve if careless. The first solution works but is cumbersome. Creating random new groups to hold one user can become difficult to manage. So, what do we do?
To give permissions to a specific user, we’ll use a tool called setfacl.
Creating a File and Denying Permissions
Let’s set the test environment. In this example, we’ll use a file called “ownedbyroot”. Let’s deny permissions to everyone else using the command:
chmod og-rwx ownedbyroot
As you can see, this reserves exclusive access for the owner of the file. In this case, root:
If I try to view the file as another user, I’m denied access:
What if I want to give access to this user? And this user alone? We can do this with the setfacl command instead.
Using Setfacl to Change User Specific File Permissions
This is the syntax to use for the setfacl command. The “-m” option tells setfacl to expect an Access Control List (ACL):
setfacl -m u:<username>:<permissions> <file|directory>
To give “read” and “write” access to the “bhagwad” user, we’ll use this command:
setfacl -m u:bhagwad:rw ownedbyroot
You can get the complete documentation for the setfacl command on this page. To control access for a specific group, you can use the “g” option:
setfacl -m g:<group>:<permissions> <file|directory>
To get the list of permissions applied to a file, use the getfacl command:
You can see in the screenshot that the user “bhagwad” has been assigned “rw” rights:
Testing File Access
So let’s test setfacl and see if it works. In the screenshot below, I first “su” into another user and try to overwrite the file. As you can see, I get a “Permission Denied” message. This is to expected since my first chmod command removed access rights for all users but the owner:
However, if I “su” into the user “bhagwad” and use the same command, I succeed. This is due to the setfacl command.
You can use setfacl to create any number of special permissions. This avoids creating new groups and changing owners. It’s a flexible and powerful tool based on the concept of ACL’s. Make sure to mount your partition with “acl” option enabled. Most modern distros use ACL, so you shouldn’t have any problems using it.