Setgid 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 бит установлен на любой каталог, все подкаталоги и файлы, созданные внутри получат те же пермишены что и группы в качестве основного каталога.

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

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

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

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

Найти SGID файлы

Читайте также:  Не качается дискорд windows 10

Найти все файлы с использованием 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» завершена.

Источник

SetUID, SetGID, and Sticky Bits in Linux File Permissions

As explained in the article Permissions in Linux, Linux uses a combination of bits to store the permissions of a file. We can change the permissions using the chmod command, which essentially changes the ‘r’, ‘w’ and ‘x’ characters associated with the file.

Further, the ownership of files also depends on the uid (user ID) and the gid (group ID) of the creator, as discussed in this article. Similarly, when we launch a process, it runs with the uid and gid of the user who launched it.

Attention reader! Don’t stop learning now. Get hold of all the important CS Theory concepts for SDE interviews with the CS Theory Course at a student-friendly price and become industry ready.

1. The setuid bit
This bit is present for files which have executable permissions. The setuid bit simply indicates that when running the executable, it will set its permissions to that of the user who created it (owner), instead of setting it to the user who launched it. Similarly, there is a setgid bit which does the same for the gid .

To locate the setuid , look for an ‘s’ instead of an ‘x’ in the executable bit of the file permissions.

An example of an executable with setuid permission is passwd , as can be seen in the following output.

This returns the following output:

As we can observe, the ‘x’ is replaced by an ‘s’ in the user section of the file permissions.

To set the setuid bit, use the following command.

To remove the setuid bit, use the following command.

2. The setgid bit

The setgid affects both files as well as directories. When used on a file, it executes with the privileges of the group of the user who owns it instead of executing with those of the group of the user who executed it.
When the bit is set for a directory, the set of files in that directory will have the same group as the group of the parent directory, and not that of the user who created those files. This is used for file sharing since they can be now modified by all the users who are part of the group of the parent directory.

To locate the setgid bit, look for an ‘s’ in the group section of the file permissions, as shown in the example below.

To set the setgid bit, use the following command.

To remove the setgid bit, use the following command.

Security Risks

The setuid bit is indeed quite useful in various applications, however, the executable programs supporting this feature should be carefully designed so as to not compromise on any security risks that follow, such as buffer overruns and path injection. If a vulnerable program runs with root privileges, the attacker could gain root access to the system through it. To dodge such possibilities, some operating systems ignore the setuid bit for executable shell scripts.

3. The sticky bit
The sticky bit was initially introduced to ‘stick’ an executable program’s text segment in the swap space even after the program has completed execution, to speed up the subsequent runs of the same program. However, these days the sticky bit means something entirely different.

When a directory has the sticky bit set, its files can be deleted or renamed only by the file owner, directory owner and the root user. The command below shows how the sticky bit can be set.

Читайте также:  Что станет с windows phone

Simply look for a ‘t’ character in the file permissions to locate the sticky bit. The snippet below shows how we can set the sticky bit for some directory “Gatos”, and how it prevents the new user from deleting a file in the directory.

To remove the sticky bit, simply use the following command.

Since deleting a file is controlled by the write permission of the file, practical uses of the sticky bit involve world-writable directories such as ‘/tmp’ so that the delete permissions are reserved only for the owners of the file.

Источник

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.

Читайте также:  Yota many mac os

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!

Источник

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