Sticky bit linux ��� ��� �����

linux-notes.org

Стандартные права (SUID, SGID, Sticky bit) в Unix/Linux

Использование «sticky bit» прав в Unix/Linux

Unix является многопользовательской ОС и в основном, устроен так, что несколько пользователей могут работать одновременно. Таким образом, программа которая находится в памяти требует меньше времени чтобы начать свою работу. Таким образом, когда один пользователь только что использовал программу, а затем новый пользователь хочет использовать ту же самую программу, то 2-й юзверь не будет иметь временной задержки для инициализации утилиты.

Установка Sticky Bit

Выставляем sticky bit на файл:

  • — T — означает, что разрешения на выполнение отключены.
  • — t — означает, что права на выполнение включены.

Или можно еще использовать следующую команду:

Sticky bit, в основном используется в общих каталогах, таких как /var или /tmp, поскольку пользователи могут создавать файлы, читать и выполнять их, принадлежащие другим пользователям, но не могут удалять файлы, принадлежащие другим пользователям. Например, если пользователь (предположим bob) создает файл с именем /tmp/bob, то другой пользователь (допустим tom) не может удалить этот файл, даже если в каталоге /tmp есть разрешение 777. Если sticky bit не установлен, то tom юзер может удалить /tmp/bob, так как файл /tmp/bob наследует разрешения родительского каталога.

Использование SUID ( Set User ID) прав в Unix/Linux

setuid (сокращения от англ. set user ID upon execution — «установка ID пользователя во время выполнения) являются флагами прав доступа в Unix, которые разрешают пользователям запускать исполняемые файлы с правами владельца исполняемого файла. Иногда файлы требуют разрешения на выполнение для пользователей, которые не являются членами группы владельца, в этом случае вам потребуется предоставить специальные разрешения на выполнение. Когда SUID установлен, пользователь может запускать любую программу, такую как владелец программы.

Установка SUID бит на файл.

Если SUID бит установлен на файл и пользователь выполнил его. Процесс будет иметь те же права что и владелец файла.

Например: команда passwd имеет SUID bit. Когда обычный пользователь захочет изменит свой пароль в файле /etc/passwd или /etc/shadow, то у него ничего не получиться, т.к нужны права суперпользователя (процесс командны PASSWD всегда работает с правами суперюзера).

Предположим, что я получил исполняемый файл «filename», и мне нужно установить SUID на этот файл, перейдите в командную строку и выпуск команду:

Теперь проверьте разрешения на файл с командой:

Наблюдайте за «s» буквой, которая была добавлена ​​для SUID бита:

Чтобы выставить SUID для всех папок и файлов, используем:

Найти SUID файлы

Найти все SUID файлы для «root» пользователя:

Найти все SUID и SGID файлы:

Использование SGID ( Set Group ID ) прав в Unix/Linux

setgid (сокращения от англ. set group ID upon execution — «установка ID группы во время выполнения») являются флагами прав доступа в Unix, которые разрешают пользователям запускать исполняемые файлы с правами группы исполняемого файла.

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

Установка бита SUID / SGID

Если SGID бит установлен на любой каталог, все подкаталоги и файлы, созданные внутри получат те же пермишены что и группы в качестве основного каталога.

Читайте также:  Windows киностудия инструкция по применению

Устанавливаем SGID на директорию:

Теперь, переключаемся на другого пользователя и создаем файл в папке /home/captain/test_dir:

В приведенном выше примере test_file.txt создался с группой root.

Чтобы выставить SGID для всех папок и файлов, используем:

Найти SGID файлы

Найти все файлы с использованием SGID бита, для root пользователя:

Найти все SUID и SGID файлы:

Зачем нужены SUID и SGID?

Есть достаточно много программ и файлов, которые должны принадлежать пользователю root, и в то же время – простые пользователи должны иметь возможность выполнять его. Для примера – утилита passwd, которая находится в каталоге /usr/bin/passwd и которая имеет дело с файлом /etc/passwd, редактировать который может только пользователь root.

Вот еще полезное чтиво:

Команда chmod также может использоваться для установки или отмены следующих значений в качестве префикса для обычных трех числовых привилегий:

  • 0 — setuid, setgid, sticky bits не установлены.
  • 1 — Установить sticky bit.
  • 2 -Установить setgid bit.
  • 3 -Установить setgid и sticky bits.
  • 4 -Установить setuid bit.
  • 5 -Установить setuid и sticky bits.
  • 6 — Установить setuid и setgid bit-ы.
  • 7 — setuid, setgid, sticky bits активированы.

Тема «Стандартные права (SUID, SGID, Sticky bit) в Unix/Linux» завершена.

Источник

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.

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.

Читайте также:  Linux определение подключенных устройств

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.

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.

Источник

What is a sticky Bit and how to set it in Linux?

Today we will see how to set Sticky Bit in Linux. This is next to SGID in our ongoing File and Folder permissions series in Linux. We already discussed about CHMOD, UMASK, CHOWN, CHGRP, SGID and SUID file and folder permissions etc in our the previous posts. In this post we will see

  • What is Sticky Bit?
  • Why we require Sticky Bit?
  • Where we are going to implement Sticky Bit?
  • How to implement Sticky Bit in Linux?

What is Sticky Bit?

Sticky Bit is mainly used on folders in order to avoid deletion of a folder and it’s content by other users though they having write permissions on the folder contents. If Sticky bit is enabled on a folder, the folder contents are deleted by only owner who created them and the root user. No one else can delete other users data in this folder(Where sticky bit is set). This is a security measure to avoid deletion of critical folders and their content(sub-folders and files), though other users have full permissions.

Learn Sticky Bit with examples:

Example: Create a project(A folder) where people will try to dump files for sharing, but they should not delete the files created by other users.

How can I setup Sticky Bit for a Folder?

Sticky Bit can be set in two ways

  1. Symbolic way (t,represents sticky bit)
  2. Numerical/octal way (1, Sticky Bit bit as value 1)

Use chmod command to set Sticky Bit on Folder: /opt/dump/

Symbolic way:

Let me explain above command, We are setting Sticky Bit(+t) to folder /opt/dump by using chmod command.

Numerical way:

Here in 1757, 1 indicates Sticky Bit set, 7 for full permissions for owner, 5 for read and execute permissions for group, and full permissions for others.

Checking if a folder is set with Sticky Bit or not?

Use ls -l to check if the x in others permissions field is replaced by t or T

For example: /opt/dump/ listing before and after Sticky Bit set

Before Sticky Bit set:

After Sticky Bit set:

Now sticky bit is set, let us check if user “temp” can delete this folder which is created xyz user.

if you observe other user is unable to delete the folder /opt/dump. And now content in this folder such as files and folders can be deleted by their respective owners who created them. No one can delete other users data in this folder though they have full permissions.

I am seeing “T” ie Capital s in the file permissions, what’s that?

After setting Sticky Bit to a file/folder, if you see ‘T’ in the file permission area that indicates the file/folder does not have executable permissions for all users on that particular file/folder.

Sticky bit without Executable permissions:

so if you want executable permissions, Apply executable permissions to the file.
chmod o+x /opt/dump/
ls -l
command output:
-rwxr-xrwt 1 xyz xyzgroup 0 Dec 5 11:24 /opt/dump/
Sticky bit with Executable permissions:

you should see a smaller ‘t’ in the executable permission position.

How can I find all the Sticky Bit set files in Linux/Unix.

The above find command will check all the files which is set with Sticky Bit bit(1000).

Can I set Sticky Bit for files?

Yes, but most of the time it’s not required.

How can I remove Sticky Bit bit on a file/folder?

Источник

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