Linux. Files. Permissions: различия между версиями

Материал из Wiki
Перейти к навигации Перейти к поиску
Строка 1: Строка 1:
[[Категория:Self-education]]
[[Категория:Self-education]]
__ОБЯЗАТЕЛЬНОЕ_ОГЛАВЛЕНИЕ__
__ОБЯЗАТЕЛЬНОЕ_ОГЛАВЛЕНИЕ__
= File permissions =
== What are octal values? ==
When Linux file permissions are represented by numbers, it's called numeric mode. In numeric mode, a three-digit value represents specific file permissions (for example, 744.) These are called octal values. The first digit is for owner permissions, the second digit is for group permissions, and the third is for other users. Each permission has a numeric value assigned to it:
* r (read): 4
* w (write): 2
* x (execute): 1
In the permission value 744, the first digit corresponds to the user, the second digit to the group, and the third digit to others. By adding up the value of each user classification, you can find the file permissions.
For example, a file might have read, write, and execute permissions for its owner, and only read permission for all other users. That looks like this:
* Owner: rwx = 4+2+1 = 7
* Group: r-- = 4+0+0 = 4
* Others: r-- = 4+0+0 = 4
The results produce the three-digit value 744.


= File types =
= File types =

Версия 22:10, 26 ноября 2024


File permissions

What are octal values?

When Linux file permissions are represented by numbers, it's called numeric mode. In numeric mode, a three-digit value represents specific file permissions (for example, 744.) These are called octal values. The first digit is for owner permissions, the second digit is for group permissions, and the third is for other users. Each permission has a numeric value assigned to it:

  • r (read): 4
  • w (write): 2
  • x (execute): 1

In the permission value 744, the first digit corresponds to the user, the second digit to the group, and the third digit to others. By adding up the value of each user classification, you can find the file permissions.

For example, a file might have read, write, and execute permissions for its owner, and only read permission for all other users. That looks like this:

  • Owner: rwx = 4+2+1 = 7
  • Group: r-- = 4+0+0 = 4
  • Others: r-- = 4+0+0 = 4

The results produce the three-digit value 744.

File types

The file type is one of the following characters:

    -  regular file

    b  block special file

    c  character special file (disk)

    C  high performance ("contiguous data") file

    d  directory

    D  door (Solaris 2.5 and up)

    l  symbolic link

    M  off-line ("migrated") file (Cray DMF)

    n  network special file (HP-UX)

    p  FIFO (named pipe)

    P  port (Solaris 10 and up)

    s  socket

    ?  some other file type

Посмотреть все аттрибуты файла

stat ./Тест.part03.rar

  File: «./Тест.part03.rar»

  Size: 5146762    Blocks: 10056      IO Block: 4096   обычный файл

Device: 871h/2161d Inode: 8650784     Links: 1

Access: (0760/-rwxrw----)  Uid: ( 3131/tmb_chishko)   Gid: (  513/Domain Users)

Access: 2019-11-08 13:14:28.768582082 +0400

Modify: 2019-11-06 17:03:47.109375000 +0400

Change: 2019-11-08 13:14:29.065585726 +0400

Timestamps

    There are 3 kind of "timestamps":

        Access - the last time the file was read

        Modify - the last time the file was modified (content has been modified)

        Change - the last time meta data of the file was changed (e.g. permissions)

Аттрибуты дополнительные

Просмотреть аттрибуты

// создадим файл

touch keep.txt

// просмотрим аттрибуты

lsattr keep.txt

-------------e-- keep.txt

// создадим аттрибут "только для чтения"

sudo chattr +i keep.txt

// теперь даже root не сможет удалить этот файл

lsattr keep.txt

----i--------e-- keep.txt

// удалим аттрибут "только для чтения"

sudo chattr -i keep.txt

// просмотрим

lsattr keep.txt

-------------e-- keep.txt

SUID, GUID

Настройка Setuid

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

root@ruvds-hrc [~]# which sudo /usr/bin/sudo
root@ruvds-hrc [~]# ls -l /usr/bin/sudo
-rwsr-xr-x 1 root root 125308 Feb 20 14:15 /usr/bin/sudo

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

Установка бита setuid не представляет сложности. Для этого используется команда:

root@ruvds-hrc [~]# chmod u+s <filename>

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

root@ruvds-hrc [~]# touch myfile
root@ruvds-hrc [~]# ls -l myfile
-rw-rw-r-- 1 test test 0 Mar 25 17:59 myfile

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

root@ruvds-hrc [~]# chmod u+s myfile 
root@ruvds-hrc [~]# ls -l myfile
-rwSrw-r-- 1 test test 0 Mar 25 12:00 myfile

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

root@ruvds-hrc [~]#  chmod u+x myfile 
root@ruvds-hrc [~]#  ls -l 
total 0
-rwsrw-r-- 1 test test 0 Mar 25 12:59 myfile

Настройка Setgid

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

root@ruvds-hrc [~]#  which crontab
/usr/bin/crontab
root@ruvds-hrc [~]#  ls -l /usr/bin/crontab
-rwxr-sr-x 1 root crontab 34021 Feb 12 2017 /usr/bin/crontab

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

Рассмотрим на примере создания нового файл с именем myfile2.

root@ruvds-hrc [~]#  touch myfile2
root@ruvds-hrc [~]#  ls -l myfile2
-rw-rw-r-- 1 test test 0 Mar 25 19:25 myfile2

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

root@ruvds-hrc [~]#  chmod g+s myfile2
root@ruvds-hrc [~]#  ls -l myfile2
-rw-rwSr-- 1 test test 0 Mar 25 19:25 myfile2

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

root@ruvds-hrc [~]#  chmod g+x myfile2
root@ruvds-hrc [~]#  ls -l
total 0
-rwsrw-r-- 1 test test 0 Mar 25 19:25 myfile
-rw-rwsr-- 1 test test 0 Mar 25 19:25 myfile2

Sticky bit

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

chmod 1777 /tmp

Freebsd расширенные атрибуты

https://www.freebsd.org/doc/ru_RU.KOI8-R/books/handbook/fs-acl.html

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

// или не изменяться права доступа даже из под root.

// это значит что на файл установлены дополнительные атрибуты ACL

// увидеть это можно через "ls -lao"

// "+" означает что на файле имеются расширенные атрибуты ACL

ls -lao /mnt/raid1/share/ПТК.xlsx

...

-rwxrw-rw-+  1 root  wheel  uarch 17301 Jul  9 08:26 ПТК.xlsx

...

// смотрим атрибуты

getfacl /mnt/raid1/share/ПТК.xlsx

# file: /mnt/raid1/share/ПТК.xlsx

# owner: root

# group: wheel

            owner@:rwxpD-aARWcCo-:-------:allow

            group@:rw-p--a-R-c---:-------:allow

         everyone@:rw-p--a-R-c---:-------:allow

// сбрасываем атрибуты

// Параметр -k удалит все установленные на данный момент ACL из файла или файловой системы.

// Более предпочтительный метод это использование параметра -b, который оставит необходимые для работы ACL поля.

setfacl -b /mnt/raid1/share/ПТК.xlsx

// смотрим

getfacl /mnt/raid1/share/ПТК.xlsx

# file: /mnt/raid1/share/ПТК.xlsx

# owner: root

# group: wheel

            owner@:rwxp--aARWcCos:-------:allow

            group@:rwxp--a-R-c--s:-------:allow

         everyone@:rwxp--a-R-c--s:-------:allow

--------------------------------------------------------------------------------