Introduction
To create a secure environment in Linux, you need to learn about user groups and permissions. For example, if you work in a company and you want the finance department to read a file but not make any modification to it, then you need to use permissions in Linux. It is a must for every programmer working with Linux nowadays.
Prerequisites
To follow along with this tutorial, you should have:
- Familiarity with the Linux operating system.
File permissions
Let’s start by talking about the ownership of Linux files.
- User: the owner of the file (person who created the file).
- Group: the group can contain multiple users. Therefore, all users in that group will have the same permissions. It makes things easier than assign permission for every user you want.
- Other: any person has access to that file, that person has neither created the file, nor are they in any group which has access to that file.
When you perform the following command:
ls -l
Then you will see the file’s permissions, like the following:
The characters mean:
- ‘r’ = read.
- ‘w’ = write.
- ‘x’ = execute.
- ‘-’ = no permission.
As we see above, the empty first part means that it is a file. If it were a directory then it will be the letter “d” instead. The second part means that the user “Home” has read and write permissions but he does not have the execute one. The group and others have only the read permission.
Let’s change the permissions using the
chmod
command.chmod o+w section.txt
This command will add the write permission for other users to my text file “section.txt”.
Now if you try to execute ls -l
then you will see -rw-r--rw-
.
“o” refers to others, “g” for the group, “u” for the user, and “a” for all.
Now let’s add the execute permission to the user with:
chmod u+x section.txt
If you want to remove the permission, you can use the same method but with “-” instead of “+”. For example, let’s remove the execute permission from the user by:
chmod u-x section.txt
And the permissions now are: -rw-r--rw-
User accounts
Create a user
We can create a new user account by issuing the following command:
sudo useradd testuser
User groups
A group is a collection of users. The primary purpose of the groups is to define a set of privileges like read, write, or execute permission for a given resource that can be shared among the users within the group.
Create a group
You can see all of the groups you have by opening the following file:
cat /etc/group
Let’s create a group with the name of section by:
sudo groupadd section
List users group
Get Apache user
Add user to a group
We will add the testuser user to the section group by:
sudo usermod -aG section testuser
Delete user from a group
You can delete the testuser from the group with:
sudo gpasswd -d testuser section
Delete a group
Let’s delete the previous group by:
sudo groupdel section