Linux set sticky bit

How Do I Set Up Setuid, Setgid, and Sticky Bits on Linux?

What Are Linux File Permissions?

Setuid, Setgid and Sticky Bits are special types of Unix/Linux file permission sets that permit certain users to run specific programs with elevated privileges. Ultimately the permissions that are set on a file determine what users can read, write or execute the file. Linux provides more advanced file permissions that allow you to do more specific things with a file, or directory.В Typically, these file permissions are used to allow a user to do certain tasks with elevated privileges (allow them to do things they normally are not permitted to do). This is accomplished with three distinct permission settings.В They are setuid, setgid, and the sticky bit.

This article is intended for a user or administrator who already has a good working knowledge of the basic Linux file permission system. If you are unfamiliar with this topic, we have an excellent tutorial on Linux file permissions. Let’s begin by reviewing each of these permission sets and how they interact with our system.

Symbolic Permission Notation

— no permission
—x execute
-w- write
-wx write and execute
r— read
r-x read and execute
rw- read and write
rwx read, write and execute

Numeric Permission Notation

The numeric notation system uses the digits 1 through 7, with each corresponding to a different symbolic permission set:

0 — no permission
1 —x execute
2 -w- write
3 -wx write and execute
4 r— read
5 r-x read and execute
6 rw- read and write
7 rwx read, write and execute

What Each Type Controls

Read: Display the contents of a file. You may be able to open it in text editors like Vim, but you will not be able to save any changes to the file unless you also have write permissions.

Write: Make changes to a file or folder/directory.

Execute: Execute (a.k.a. Run) a file. Examples include compiled binaries and shell scripts.

What is Setuid?

Setuid is a Linux file permission setting that allows a user to execute that file or program with the permission of the owner of that file. This is primarily used to elevate the privileges of the current user. If a file is “setuid” and is owned by the user “root” then a user that has the ability to execute that program will do so as the user root instead of themselves. The most common example of this in Linux is ‘sudo’. In this example, the user ‘test’ located the executable ‘sudo’ and did a full listing of it with the ‘ls -l’ command.

If you look at the permissions level of the ‘sudo’ executable, you can see the ‘s’ in the permissions for the user where normally there would be an ‘x’.В Also, notice that this file is owned by the user ‘root’ (the super-user) and that the file is executable by the world (the last ‘x’ in the permissions).В This indicates that when a user executes this program, the operating system will execute that file not as the user ‘test’, but as the user ‘root‘. In the matter of using the ‘sudo’ command, this allows a normal user to perform elevated system functions without having to log in as the root user.

How Do I Set Up Setuid?

Setting the ‘setuid’ permission is as simple as setting any other permission in Linux. The file ownership is modified using the command. An example command to set this would be as follows.

Читайте также:  Gigabyte b450m ds3h установка windows

In this example, we will create a file called ‘myfile’ using the command ‘touch’ and then we will examine its permissions with the ‘ls -l’ command.

Notice that the file does not have the execute permissions for user, group, or world. We will add the setuid bit as seen below.

This output looks a little different from what we were expecting. The lowercase ‘s’ we were looking for is the now a capital ‘S.’ This signifies that the setuid IS set, but the user that owns the file does not have execute permissions. We can add that permission using the ‘chmod u+x’ command.

What is Setgid?

Setgid, when used on files, is very similar to setuid. A process, when executed, will run as the group that owns the file. A typical example of a file that uses this is the ‘crontab’ command.

How Do I Set Up Setgid?

Similar to ‘setuid,’ ‘setgid’ is inserted with the ‘chmod g+s’ command. Let’s create a new file called ‘myfile2’.

Now we will run the ‘chmod g+s‘ command and review the results.

Again we see the capital ‘S’ is set, but we can modify that.

Setgid on Directories

Applying the setgid permission on a directory has as different behavior. A directory that has ‘setgid’ on it will cause all files that are created in that directory to be owned by the group of the directory as opposed to the group of the owner. First, we create a directory.

Then we change the group ownership of the directory by using the ‘chgrp‘ command, and then we can add the ‘setgid’ permission like before.

Let’s test it out by creating a file in that directory. All other files in this tutorial were created this way and had ‘test’ as the group. Because ‘setgid’ is set on the directory and it is owned by group ‘test2’, this file will get ‘test2’ as its group.

What Is A Sticky Bit?

The final special permission is the ‘sticky bit.’ When this is set on a directory, the files in that directory can only be removed by the owner. A typical use of this is ‘/tmp/.’ The /tmp directory can be written to by any user, but other users cannot delete the files of others.В

Notice that /tmp can be written to by everyone but has the ‘t’ in place of the ‘x’ at the end of the permissions list. This means it has the sticky bit.

How Do I Set Up A Sticky Bit?

The sticky bit is set with ‘chmod +t’ command.

Setting Special Permissions With Number Notation

You may remember from the definitions above that permissions can be set with a series of three numbers. The numbers represent the permissions for owner, group, and world, respectively. To determine the number you want to set, you can use x=1, w=2, and r=4. You add the numbers together to get the permission number. If we wanted to have read, write, and execute permissions, we would use 7. Read and write would be 6. Just read is 4. An example to set the file to read, write, and execute for owner, read and execute for group and world would look like this:

For the special permissions, you prepend these numbers with another number where 4 is setuid, 2 is setgid, and 1 is the sticky bit. The following commands are all the same (assuming the file has the permissions we set above).

Removing Special Permissions

To remove special permissions, we can use the same chmod commands with a ‘’ instead of a ‘+.’

Conclusion

All in all, these special permissions are very useful for separating the ability of a user or group to read, write or execute a file or affect a change on a folder.

Reserve Your Spot Now!

Give us a call at 800.580.4985, or open a chat or ticket with us to speak with one of our knowledgeable Solutions or Experienced Hosting advisors to learn how you can take advantage of these techniques today!

Источник

Использование SETUID, SETGID и Sticky bit для расширенной настройки прав доступа в операционных системах Linux

975 просмотров 2 2021-03-25 2021-03-30

В этой статье мы расскажем, как использовать специальные биты разрешений в операционных системах Linux.
Речь пойдет о трех битах – Setuid, Setgid и Sticky Bit. Это специальные типы разрешений позволяют задавать расширенные права доступа на файлы или каталоги.
Статья будет полезна пользователям и администраторам, которые уже знакомы с настройкой базовых прав в операционных системах Linux. Итак, давайте преступим.

Читайте также:  Как убрать блокировку компьютера windows 10 при запуске

Коротко о правах доступа в Linux

В операционных системах Linux используются 3 базовых права доступа – на чтение (read), запись (write) и исполнение (execute). Соответственно, права назначаются пользователю (user), группе (group) и всем остальным (world). Рассмотрим их символьные обозначения:

В случае числового обозначения прав доступа используются цифры от 0 до 7, где каждая цифра соответствует определенному набору прав доступа:

Настройка Setuid

Setuid – это бит разрешения, который позволяет пользователю запускать исполняемый файл с правами владельца этого файла. Другими словами, использование этого бита позволяет нам поднять привилегии пользователя в случае, если это необходимо. Классический пример использования этого бита в операционной системе это команда sudo.

Как мы видим на месте, где обычно установлен классический бит x (на исполнение), у нас выставлен специальный бит s. Это позволяет обычному пользователю системы выполнять команды с повышенными привилегиями без необходимости входа в систему как root, разумеется зная пароль пользователя root.
Установка бита setuid не представляет сложности. Для этого используется команда:

Рассмотрим на примере. Создадим файл с именем myfile, а затем проверим его разрешения с помощью команды ls -l.

Как видим, файл не имеет разрешений на выполнение для пользователя, группы и остальных. Добавим бит setuid:

Обратим внимание, что вместо ожидаемой буквы «s», видим заглавную «S». Почему? Это случается, если setuid установлен, но сам владелец файла не имеет прав на его выполнение. Добавим это разрешение с помощью команды chmod u + x.

Настройка Setgid

Принцип работы Setgid очень похож на setuid с отличием, что файл будет запускаться пользователем от имени группы, которая владеет файлом. Иллюстрирует работу этого бита команда crontab: .

Теперь перейдем к настройке этого бита. Аналогично setuid, бит setgid выставляется с помощью команды chmod g + s .
Рассмотрим на примере создания нового файл с именем myfile2.

Выполним команду chmod g + s и посмотрим результаты.

Как разобрались выше, меняем заглавную « S » путем выдачи прав на исполнение группе-владельцу:

Настройка Sticky Bit

Последний специальный бит разрешения – это Sticky Bit . В случае, если этот бит установлен для папки, то файлы в этой папке могут быть удалены только их владельцем. Пример использования этого бита в операционной системе это системная папка /tmp . Эта папка разрешена на запись любому пользователю, но удалять файлы в ней могут только пользователи, являющиеся владельцами этих файлов.

Символ «t» указывает, что на папку установлен Sticky Bit.

Удаление специальных битов разрешений

Удаляем эти биты также командой chmod, только вместо « + » используем « – » .

Вывод

Мы разобрали что из себя представляют специальные биты разрешений Setuid, Setgid и Sticky bit в операционных системах Linux и как ими пользоваться на практике. Умение использовать эти биты позволит вам произвести более гибкую настройку прав доступа к ресурсам вашего сервера.

Источник

Sticky Bit, SUID and SGID in Linux with Examples

In this article, we explain special permissions that work on files and directories named as Sticky bit, SUID and SGID.

The sticky bit works on directories only. If a user wants to create or delete a file/directory in some directory, he needs write permission on that directory. The write permission on a directory gives a user the privilege to create a file as well as the privilege to remove it.

The /tmp directory is the directory for temporary files/directories. This directory has all the rights on all the three levels because all the users need to create/delete their temporary files. But as the users have write permission on this directory, they can delete any file in this directory. The permissions of that file do not have any effect on deletion.

But with sticky bit set on a directory, anyone can create a file/directory in it, but can delete his own files only. Files owned by other users cannot be deleted.

Sticky bit — How to view and set

You could notice t tag added to /tmp directory and it means bit is set for this directory.

In Linux sticky bit can be set with chmod command. You can use +t tag to add and -t tag to delete sticky bit.

Note: In Unix flavored OS, sticky bit has a different purpose but we are not discussing it here.

What is SUID Bit and How to set it

When an executable file runs, it runs under the ownership of the user who has executed it. It means that when student user runs ls command, then the corresponding process will run under the ownership of student. The SUID bit, also known as Set User ID bit, overwrites this behavior. If SUID bit is set on a program, then that program will run as the owner of that file, irrespective of who is executing it.

Читайте также:  Arch linux at work

The passwd command in Linux has SUID bit set.

This can be seen in the third field of permissions. The ‘s’ in place of ‘x’ indicates that SUID bit is set. With SUID bit set, when a normal user (say student) runs the passwd command, the command runs with the ownership of ‘root’, and not as student, because root is the owner of this file. This behavior is required because the passwords are stored in the /etc/shadow file, which has no permission on group or other level.

You need to understand that all users cannot be given read or write permission on this file for security reasons; otherwise, they will read/change the passwords of other users. So this causes a problem that if the users don’t have permission on this file, then how will they change their own passwords? So SUID bit solves the problem. The passwd command has SUID bit set, so when normal users execute this command, they run it with the ownership of root, i.e. the owner of passwd command.

How to Set and unset SUID bit

This is to be noted that SUID bit works on files only. To set the SUID bit on a file, use the chmod command as follows

The numeric method for changing permissions can also be used. Suppose if the normal permissions for a file are 744, then with SUID bit set, these will become 4744. SUID bit has value 4.

How SGID Bit work on file and directory

Unlike SUID bit, SGID bit works on both files and directories, but it has a different meaning in both cases.

On files:

For file, it has similar meaning as the SUID bit, i.e. when any user executes a file with SGID bit set on it, it will always be executed with the group ownership of that file, irrespective of who is running it. For example, the file /sbin/netreport has SGID bit set, which can be seen in the ‘s’ instead of ‘x’ in group permissions.

This file has group ownership of root group. So when a user (say student) executes it, then the corresponding process will not have group ownership of student, but that of root group.

On directories:

Now let’s talk about SGID on directories. SGID on directories is used for creating collaborative directories. To understand SGID bit on directories, consider the following scenario:

Suppose three users jack, jones and jenny are working together on some project. All of them belong to a group named javaproject. For the course of the project, they need to share all the files related to the project. All of them must be able to see each other’s file. This can be done simply by providing read permission on group level. Further, suppose that the directory used for the project is «/javaproject».

Here, a problem arises that when a file is created, it belongs to the primary group of the user who created the file. So, when different users create their files in this directory, those files will not have group ownership of javaproject group.

What we do for our problem is that we set the group of /javaproject directory to be javaproject group, and set the SGID bit set on it. When SGID bit is set on a directory, all the files and directory created within it has the group ownership of the group associated with that directory. It means that after setting SGID bit on /javaproject directory, all the files and directories being created in this directory will have the group ownership of «javaproject» group. Moreover, this behavior is recursive, i.e. the directories created in this directory will have SGID bit set as well. The permissions for the new directory will also be same as that of /javaproject directory.

The SGID bit can be set with chmod command as follows:

Now when jones user creates a file in this directory, it is created under the group ownership of javaproject group.

The numeric value corresponding to SGID bit is 2. So to add SGID bit numerically, use the following command:

Thanks for reading this article and refer sticky bit wiki page as well.

Источник

Оцените статью