Sgid linux ��� ���

🧟♀️ StickyBit, SUID и SGID в Linux с примерами

В этой статье мы расскажем о специальных разрешениях, которые работают с файлами и каталогами, которые называются Stickybit, SUID и SGID.

Sticky работает только для каталогов.

Если пользователь хочет создать или удалить файл / каталог в каком-либо каталоге, ему нужно разрешение на запись в этот каталог.

Разрешение на запись в каталог дает пользователю право создавать файл, а также право удалять его.

Каталог /tmp – это каталог для временных файлов / каталогов.

Этот каталог обладает всеми правами на всех трех уровнях, поскольку все пользователи должны создавать/удалять свои временные файлы.

Но так как пользователи имеют разрешение на запись в этот каталог, они могут удалить любой файл в этом каталоге.

Разрешения этого файла не влияют на удаление.

Но с установленным в каталоге стики битом любой может создать в нем файл / каталог, но может удалить только свои собственные файлы.

Файлы, принадлежащие другим пользователям, не могут быть удалены.

stickybit – Как просмотреть и установить

Вы можете заметить, что тег t добавлен в каталог /tmp, и это означает, что для этого каталога установлен бит.

В Linux стики бит может быть установлен командой chmod.

Вы можете использовать тег + t, чтобы добавить, и тег -t, чтобы удалить бит.

Примечание. В ОС Unix stickybit имеет другое назначение, но мы не обсуждаем его здесь.

Что такое SUID бит и как его установить

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

Это означает, что когда пользователь student запускает команду ls, соответствующий процесс будет выполняться под управлением пользователя student.

Бит SUID, также известный как бит установки идентификатора пользователя, перезаписывает это поведение.

Если в программе установлен бит SUID, то эта программа будет работать как владелец этого файла, независимо от того, кто его выполняет.

У команды passwd в Linux установлен бит SUID.

Это можно увидеть в третьем поле прав доступа. ‘S’ вместо ‘x’ указывает, что установлен бит SUID.

С установленным битом SUID, когда обычный пользователь (скажем, student) запускает команду passwd, команда запускается с владельцем «root», а не с учетной записью student, поскольку root является владельцем этого файла.

Это необходимо, потому что пароли хранятся в файле /etc/shadow, который не имеет разрешения на групповом или другом уровне.

Вы должны понимать, что все пользователи не могут получить разрешение на чтение или запись этого файла по соображениям безопасности; в противном случае они будут читать / изменять пароли других пользователей.

Таким образом, это вызывает проблему: если у пользователей нет прав доступа к этому файлу, как они будут изменять свои собственные пароли?

SUID немного решает проблему.

У команды passwd установлен бит SUID, поэтому, когда обычные пользователи выполняют эту команду, они запускают ее под владельцем root, то есть владельцем команды passwd.

Как установить и сбросить бит SUID

Следует отметить, что бит SUID работает только с файлами.

Читайте также:  Как установить шрифты для linux

Чтобы установить бит SUID на файл, используйте команду chmod следующим образом

Числовой метод для изменения разрешений также может быть использован.

Предположим, что если обычные разрешения для файла равны 744, то с установленным битом SUID они станут 4744.

Бит SUID имеет значение 4.

Как SGID Bit работает с файлами и каталогоми

В отличие от бита SUID, бит SGID работает как с файлами, так и с каталогами, но в обоих случаях он имеет различное значение.

По файлам:

Для файла он имеет значение, аналогичное значению бита SUID, то есть когда любой пользователь выполняет файл с установленным битом SGID, он всегда будет выполняться с владельцем группы этого файла, независимо от того, кто его запускает.

Например, файл /sbin/netreport имеет установленный бит SGID, который можно увидеть в «s» вместо «x» в разрешениях группы.

Этот файл имеет групповое владение группой root.

Таким образом, когда пользователь (скажем, student) выполняет его, соответствующий процесс не будет принадлежать группе student, а будет принадлежать группе root.

По каталогам:

Теперь поговорим о SGID в каталогах.

SGID для каталогов используется для создания совместных каталогов.

Чтобы понять бит SGID для каталогов, рассмотрим следующий сценарий:

Предположим, что три пользователя Джек, Джонс и Дженни вместе работают над каким-то проектом.

Все они принадлежат к группе под названием javaproject.

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

Все они должны видеть файлы друг друга.

Это можно сделать, просто предоставив разрешение на чтение на уровне группы.

Далее, предположим, что каталогом, используемым для проекта, является “/javaproject”.

Здесь возникает проблема: когда файл создается, он принадлежит к основной группе пользователя, создавшего файл.

Таким образом, когда разные пользователи создают свои файлы в этом каталоге, эти файлы не будут принадлежать группе javaproject group.

Что мы делаем для решения нашей проблемы, так это то, что мы устанавливаем группу каталога /javaproject равной группе javaproject, и устанавливаем бит SGID.

Когда в каталоге установлен бит SGID, все файлы и каталоги, созданные в нем, имеют групповое владение группой, связанной с этим каталогом.

Это означает, что после установки бита SGID в каталоге /javaproject все файлы и каталоги, создаваемые в этом каталоге, будут принадлежать группе «javaproject».

Более того, это поведение является рекурсивным, то есть в каталогах, созданных в этом каталоге, также будет установлен бит SGID.

Права у нового каталога также будут такими же, как и у каталога /javaproject.

Бит SGID может быть установлен командой chmod следующим образом:

Теперь, когда пользователь jones создает файл в этом каталоге, он создается под владельцем группы javaproject.

Числовое значение, соответствующее биту SGID, равно 2. Поэтому, чтобы численно добавить бит SGID, используйте следующую команду:

Источник

Special File Permissions in Linux: SUID, GUID and Sticky Bit

File permissions and ownership are the basic and yet essential security concept in Linux. You probably are already familiar with these terms already. It typically looks like this:

Regular file permissions

Apart from these regular permissions, there are a few special file permissions and not many Linux users are aware of it.

Linux Special Permissions: SUID, GUID and Sticky Bit

To start talking about of special permissions, I am going to presume that you have some knowledge of the basic file permissions. If not, please read our excellent guide explaining Linux file permission.

Now I’m gonna show you some special permissions with new letters on Linux file system.

In this example, the passwd command, responsible to change the password of a user, has the letter s on the same place we expect to see x or — , for user permissions. It’s important to notice that this file belongs to root user and root group.

Читайте также:  Linux caps lock delay

With this permission you don’t need to give sudo access to a specific user when you want him to run some root script.

What is SUID?

When the SUID bit is set on an executable file, this means that the file will be executed with the same permissions as the owner of the executable file.

Let’s take a practical example. If you look at the binary executable file of the passwd command, it has the SUID bit set.

This means that any user running the passwd command will be running it with the same permission as root.

What’s the benefit? The passwd command needs to edit files like /etc/passwd, /etc/shadow to change the password. These files are owned by root and can only be modified by root. But thanks to the setuid flag (SUID bit), a regular user will also be able to modify these files (that are owned by root) and change his/her password.

This is the reason why you can use the passwd command to change your own password despite of the fact that the files this command modifies are owned by root.

Why can a normal user not change the password of other users?

Note that a normal user can’t change passwords for other users, only for himself/herself. But why? If you can run the passwd command as a regular user with the same permissions as root and modify the files like /etc/passwd, why can you not change the password of other users?

If you check the code for the passwd command, you’ll find that it checks the UID of the user whose password is being modified with the UID of the user that ran the command. If it doesn’t match and if the command wasn’t run by root, it throws an error.

The setuid/SUID concept is tricky and should be used with utmost cautious otherwise you’ll leave security gaps in your system. It’s an essential security concept and many commands (like ping command) and programs (like sudo) utilize it.

Now that you understand the concept SUID, let’s see how to set the SUID bit.

How to set SUID bit?

I find the symbolic way easier while setting SUID bit. You can use the chmod command in this way:

Here’s an example:

You can also use the numeric way. You just need to add a fourth digit to the normal permissions. The octal number used to set SUID is always 4.

How to remove SUID?

You can use either the symbolic mode in chmod command like this:

Or, use the numeric way with 0 instead of 4 with the permissions you want to set:

Difference between small s and capital S as SUID bit

Remember the definition of SUID? It allows a file to be executed with the same permissions as the owner of the file.

But what if the file doesn’t have execute bit set in the first place? Like this:

If you set the SUID bit, it will show a capital S, not small s:

The S as SUID flag means there is an error that you should look into. You want the file to be executed with the same permission as the owner but there is no executable permission on the file. Which means that not even the owner is allowed to execute the file and if file cannot be executed, you won’t get the permission as the owner. This fails the entire point of setting the SUID bit.

Читайте также:  Что может блокировать порт windows

How to find all files with SUID set?

If you want to search files with this permission, use find command in the terminal with option -perm.

What is SGID?

SGID is similar to SUID. With the SGID bit set, any user executing the file will have same permissions as the group owner of the file.

It’s benefit is in handling the directory. When SGID permission is applied to a directory, all sub directories and files created inside this directory will get the same group ownership as main directory (not the group ownership of the user that created the files and directories).

Open your terminal and check the permission on the file /var/local:

This folder /var/local has the letter ‘s’ on the same place you expect to see ‘x’ or ‘-‘ for group permissions.

A practical example of SGID is with Samba server for sharing files on your local network. It’s guaranteed that all new files will not lose the permissions desired, no matter who created it.

How to set SGID?

You can set the SGID bit in symbolic mode like this:

Here’s an example:

You may also use the numeric way. You just need to add a fourth digit to the normal permissions. The octal number used to SGID is always 2.

How to remove SGID bit?

Just use the -s instead of +s like this:

Removing SGID is the same as removing SGID. Use the additional 0 before the permissions you want to set:

How to find files with SGID set in Linux

To find all the files with SGID bit set, use this command:

What is a Sticky Bit?

The sticky bit works on the directory. With sticky bit set on a directory, all the files in the directory can only be deleted or renamed by the file owners only or the root.

This is typically used in the /tmp directory that works as the trash can of temporary files.

As you can see, the folder /tmp, has the letter t on the same place we expect to see x or for others permissions. This means that a user (except root) cannot delete the temporary files created by other users in the /tmp directory.

How to set the sticky bit?

As always, you can use both symbolic and numeric mode to set the sticky bit in Linux.

Here’s an example:

The numeric way is to add a fourth digit to the normal permissions. The octal number used for sticky bit is always 1.

How to remove the sticky bit:

You can use the symbolic mode:

Or the numeric mode with 0 before the regular permissions:

How to find files with sticky bit set in Linux

This command will return all files/directories in with sticky bit set:

If the directory doesn’t have the execute permission set for all, setting a sticky bit will result in showing T instead of t. An indication that things are not entirely correct with the sticky bit.

Conclusion

I’ll put this picture here to recall what you have just learned:

This flexibility to manage folders, files and all their permissions are so important in the daily work of a sysadmin. You could see that all those special permissions are not so difficult to understand but it must be used with utmost caution.

I hope this article gave you a good understanding of the SUID, GUID and Sticky Bit in Linux. If you have questions or suggestions, please drop a comment below.

Источник

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