File permissions and attributes (Русский)

From ArchWiki
Revision as of 06:10, 4 June 2020 by Duodai (talk | contribs) (add a russian link in the related articles section)

Эта статья или раздел нуждается в переводе

Примечания: В прогрессе перевода (обсуждение: Talk:File permissions and attributes (Русский)#)

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

Важно: При использовании в целях безопасности разрешения и атрибуты защищают только от атак, запускаемых из запущенной системы. Для защиты хранимых данных от злоумышленника с физическим доступом необходимо реализовать шифрование диска.

Просмотр разрешений

Для просмотра разрешений (или права файла) используйте команду ls с опцией -l для просмотра содержимого каталога, например:

$ ls -l /путь/к/директории
total 128
drwxr-xr-x 2 archie users  4096 май  5 21:03 Рабочий стол
drwxr-xr-x 6 archie users  4096 май  5 17:37 Документы
drwxr-xr-x 2 archie users  4096 май  5 13:45 Загрузки
-rw-rw-r-- 1 archie users  5120 апр 27 08:28 customers.ods
-rw-r--r-- 1 archie users  3339 апр 27 08:28 todo
-rwxr-xr-x 1 archie users  2048 май  6 12:56 myscript.sh

Здесь мы должны сосредоточиться на первом столбце. Например, обратив внимания на значение drwxrwxrwx+, каждый символ которого объясняется в следующих таблицах:

d rwx rwx rwx +
Обозначет тип файла, технически не относится к разрешениям. Смотрите типы файлов (UNIX) для ознакомления со всеми возможными значениями. Разрешения, которые имеет владелец к файлу (объяснения ниже). Разрешения, которые имеет группа к файлу (объяснения ниже). Разрешения, которые имеют все остальные пользователи к файлу (объяснения ниже). Одиночный символ, который указывает на применение альтернативного метода доступа. Пробел указывает на отсутствие альтернативного метода доступа. Символ . обозначает файл с контекстом безопасности, но без другого альтернативного метода доступа. Файл с любой другой комбинацией альтернативных методов доступа помечается символом +, например в случае Access Control Lists (Русский).

Каждая из трёх триад разрешений (rwx в примере выше) может состоять из следующих символов:

Символ Влияние на файлы Влияние на директории
Разрешение на чтение (первый символ) - Файл не может быть прочитан. Содержимое каталога не может быть показано.
r Файл можно прочитать. Содержимое каталога может быть показано.
Разрешение на запись (второй символ) - Файл не может быть изменён. Содержимое каталога не может быть изменено.
w Файл может быть изменён. Содержимое каталога может быть изменено (создание новых файлов или папок; переименовывание и удаление существующих файлов или папок); дополнительно требуется разрешение на выполнение, в противном случае, это разрешение не действует.
Разрешение на выполнение (третий символ) - Файл не может быть выполнен. Каталог не может быть доступен с помощью cd.
x Файл может быть выполнен. The directory can be accessed with cd; this is the only permission bit that in practice can be considered to be "inherited" from the ancestor directories, in fact if any folder in the path does not have the x bit set, the final file or folder cannot be accessed either, regardless of its permissions; see path_resolution(7) for more information.
s The setuid bit when found in the user triad; the setgid bit when found in the group triad; it is not found in the others triad; it also implies that x is set.
S Same as s, but x is not set; rare on regular files, and useless on folders.
t The sticky bit; it can only be found in the others triad; it also implies that x is set.
T Same as t, but x is not set; rare on regular files, and useless on folders.

See info Coreutils -n "Mode Structure" and chmod(1) for more details.

Tip: You can view permissions along a path with namei -l path.

Примеры

Давайте посмотрим несколько примеров для лучшего понимания:

drwx------ 6 archie users  4096 Июл  5 17:37 Документы

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

dr-x------ 6 archie users  4096 Июл  5 17:37 Документы

Archie имеет полный доступ за исключением создавать, переименовывать и удалять любые файлы. Он может просматривать файлы и (если позволяют разрешения к файлам) может получит доступ к существующему файлу в Документах.

d-wx------ 6 archie users  4096 Июл  5 17:37 Документы

Archie не может выполнить ls в Документах, но если он знает имя существующего файла, то он может просмотреть, переименовать и удалить или (если позволяют разрешения) получить доступ к нему. Также он может создавать новые файлы.

d--x------ 6 archie users  4096 Июл  5 17:37 Документы

Archie может только (если позволяют разрешения файла) получить доступ к тем файлам в Документах, о которых он знает. Он не может просмотреть уже существующие файлы или создавать, переименовывать и удалить любой из них.

Следует помнить, что мы уточняем права доступа к директориям, но это не имеет ничего общего с правами доступа к отдельным файлам. При создании нового файла меняется директория. Вот почему вам нужно разрешения на запись в директорию.

Давайте посмотрим на другой пример, на этот раз файл, а не каталог:

-rw-r--r-- 1 archie users  5120 Июн 27 08:28 foobar

Здесь мы видим первой буквой не d, а -. Таким образом мы знаем, что это файл, а не директория. Благодаря разрешению rw- владелец может читать и писать, но не выполнять. Может показаться странным, что у владельца нет всех трёх разрешений, но разрешение x не требуется, так как это файл текста/данных, который может быть прочитан текстовым редактором, например Gedit, EMACS или программным обеспечением подобно R, а не исполнятся самим файлом (если он содержит что-то вроде программного кода на Python, то тогда подобное вполне возможно). Для группы установлены права доступа r--, поэтому у группы есть возможность читать файл, но не записывать и не редактировать его - фактически это установка чего-либо только для чтения. Мы видим, что подобные разрешения применимы и ко всем остальным пользователям.

Изменение разрешений

chmod это команда в Linux и других Unix-подобных операционных системах, которая позволяет изменять права доступа к файлам или каталогам.

Текстовый метод

Для изменения прав доступа - или режима доступа - к файлу используйте команду chmod в терминале. Ниже приведена общая структура команды:

chmod кто=разрешения имя_файла

Где кто - любая из нескольких букв, каждая из которых обозначает, кому дано разрешение. Они следующие:

  • u: the user that owns the file.
  • g: the user group that the file belongs to.
  • o: the other users, i.e. everyone else.
  • a: all of the above; use this instead of typing ugo.

The permissions are the same as discussed in #Viewing permissions[broken link: invalid section] (r, w and x).

Теперь посмотрите на некоторые примеры использования этой команды. Предположим, вы захотели сильно защитить каталог Документы и отказать всем, кроме себя, в разрешении на чтение, запись и выполнение (или, в данном случае, поиск/просмотр) внутри него:

До: drwxr-xr-x 6 archie users 4096 Июл 5 17:37 Документы

$ chmod g= Документы
$ chmod o= Документы

После: drwx------ 6 archie users 4096 Июл 6 17:32 Документы

Здесь, поскольку вы хотите отказать в разрешениях, вы не ставите никаких букв после =, где будут введены разрешения. Из этого видно, что только разрешения владельца - это rwx, а все остальные разрешения - это -.

Это можно восстановить с помощью:

До: drwx------ 6 archie users 4096 Июл 6 17:32 Документы

$ chmod g=rx Документы
$ chmod o=rx Документы

После: drwxr-xr-x 6 archie users 4096 Июл 6 17:32 Документы

В следующем примере вы предоставляете права на чтение и выполнение группе и другим пользователям, поэтому вы ставите следующие буквы для этих прав (r и x) после =, не оставляя пробелов.

Вы можете упростить это поместив более одной буквы кто в одну и ту же команду, например:

$ chmod go=rx Документы
Note: It does not matter in which order you put the who letters or the permission letters in a chmod command: you could have chmod go=rx file or chmod og=xr file. It is all the same.

Now let us consider a second example, suppose you want to change a foobar file so that you have read and write permissions, and fellow users in the group users who may be colleagues working on foobar, can also read and write to it, but other users can only read it:

Before: -rw-r--r-- 1 archie users 5120 Jun 27 08:28 foobar

$ chmod g=rw foobar

After: -rw-rw-r-- 1 archie users 5120 Jun 27 08:28 foobar

This is exactly like the first example, but with a file, not a directory, and you grant write permission (just so as to give an example of granting every permission).

Text method shortcuts

The chmod command lets add and subtract permissions from an existing set using + or - instead of =. This is different from the above commands, which essentially re-write the permissions (e.g. to change a permission from r-- to rw-, you still need to include r as well as w after the = in the chmod command invocation. If you missed out r, it would take away the r permission as they are being re-written with the =. Using + and - avoids this by adding or taking away from the current set of permissions).

Let us try this + and - method with the previous example of adding write permissions to the group:

Before: -rw-r--r-- 1 archie users 5120 Jun 27 08:28 foobar

$ chmod g+w foobar

After: -rw-rw-r-- 1 archie users 5120 Jun 27 08:28 foobar

Another example, denying write permissions to all (a):

Before: -rw-rw-r-- 1 archie users 5120 Jun 27 08:28 foobar

$ chmod a-w foobar

After: -r--r--r-- 1 archie users 5120 Jun 27 08:28 foobar

A different shortcut is the special X mode: this is not an actual file mode, but it is often used in conjunction with the -R option to set the executable bit only for directories, and leave it unchanged for regular files, for example:

$ chmod -R a+rX ./data/

Copying permissions

It is possible to tell chmod to copy the permissions from one class, say the owner, and give those same permissions to group or even all. To do this, instead of putting r, w, or x after the =, put another who letter. e.g:

Before: -rw-r--r-- 1 archie users 5120 Jun 27 08:28 foobar

$ chmod g=u foobar

After: -rw-rw-r-- 1 archie users 5120 Jun 27 08:28 foobar

This command essentially translates to "change the permissions of group (g=), to be the same as the owning user (=u). Note that you cannot copy a set of permissions as well as grant new ones e.g.:

$ chmod g=wu foobar

In that case chmod throw an error.

Numeric method

chmod can also set permissions using numbers.

Using numbers is another method which allows you to edit the permissions for all three owner, group, and others at the same time, as well as the setuid, setgid, and sticky bits. This basic structure of the code is this:

$ chmod xxx filename

Where xxx is a 3-digit number where each digit can be anything from 0 to 7. The first digit applies to permissions for owner, the second digit applies to permissions for group, and the third digit applies to permissions for all others.

In this number notation, the values r, w, and x have their own number value:

r=4
w=2
x=1

To come up with a 3-digit number you need to consider what permissions you want owner, group, and all others to have, and then total their values up. For example, if you want to grant the owner of a directory read write and execution permissions, and you want group and everyone else to have just read and execute permissions, you would come up with the numerical values like so:

  • Owner: rwx=4+2+1=7
  • Group: r-x=4+0+1=5
  • Other: r-x=4+0+1=5
$ chmod 755 filename

This is the equivalent of using the following:

$ chmod u=rwx filename
$ chmod go=rx filename

To view the existing permissions of a file or directory in numeric form, use the stat(1) command:

$ stat -c %a filename

Where the %a option specifies output in numeric form.

Most folders and directories are set to 755 to allow reading, writing and execution to the owner, but deny writing to everyone else, and files are normally 644 to allow reading and writing for the owner but just reading for everyone else; refer to the last note on the lack of x permissions with non executable files: it is the same thing here.

To see this in action with examples consider the previous example that has been used but with this numerical method applied instead:

Before: -rw-r--r-- 1 archie users 5120 Jun 27 08:28 foobar

$ chmod 664 foobar

After: -rw-rw-r-- 1 archie users 5120 Jun 27 08:28 foobar

If this were an executable the number would be 774 if you wanted to grant executable permission to the owner and group. Alternatively if you wanted everyone to only have read permission the number would be 444. Treating r as 4, w as 2, and x as 1 is probably the easiest way to work out the numerical values for using chmod xxx filename, but there is also a binary method, where each permission has a binary number, and then that is in turn converted to a number. It is a bit more convoluted, but here included for completeness.

Consider this permission set:

-rwxr-xr--

If you put a 1 under each permission granted, and a 0 for every one not granted, the result would be something like this:

-rwxrwxr-x
 111111101

You can then convert these binary numbers:

000=0	    100=4
001=1	    101=5
010=2	    110=6
011=3	    111=7

The value of the above would therefore be 775.

Consider we wanted to remove the writable permission from group:

-rwxr-xr-x
 111101101

The value would therefore be 755 and you would use chmod 755 filename to remove the writable permission. You will notice you get the same three digit number no matter which method you use. Whether you use text or numbers will depend on personal preference and typing speed. When you want to restore a directory or file to default permissions e.g. read and write (and execute) permission to the owner but deny write permission to everyone else, it may be faster to use chmod 755/644 filename. However if you are changing the permissions to something out of the norm, it may be simpler and quicker to use the text method as opposed to trying to convert it to numbers, which may lead to a mistake. It could be argued that there is not any real significant difference in the speed of either method for a user that only needs to use chmod on occasion.

You can also use the numeric method to set the setuid, setgid, and sticky bits by using four digits.

setuid=4
setgid=2
sticky=1

For example, chmod 2777 filename will set read/write/executable bits for everyone and also enable the setgid bit.

Bulk chmod

Generally directories and files should not have the same permissions. If it is necessary to bulk modify a directory tree, use find to selectively modify one or the other.

To chmod only directories to 755:

$ find directory -type d -exec chmod 755 {} +

To chmod only files to 644:

$ find directory -type f -exec chmod 644 {} +

Changing ownership

chown changes the owner of a file or directory, which is quicker and easier than altering the permissions in some cases.

Consider the following example, making a new partition with GParted for backup data. Gparted does this all as root so everything belongs to root by default. This is all well and good but when it comes to writing data to the mounted partition, permission is denied for regular users.

brw-rw---- 1 root disk 8,    9 Jul  6 16:02 sda9
drwxr-xr-x 5 root root    4096 Jul  6 16:01 Backup

As you can see the device in /dev is owned by root, as is the mount location (/media/Backup). To change the owner of the mount location one can do the following:

Before: drwxr-xr-x 5 root root 4096 Jul 6 16:01 Backup

# chown archie /media/Backup

After: drwxr-xr-x 5 archie root 4096 Jul 6 16:01 Backup

Now the partition can have data written to it by the new owner, archie, without altering the permissions (as the owner triad already had rwx permissions).

Note:
  • chown always clears the setuid and setgid bits.
  • Non-root users cannot use chown to "give away" files they own to another user.

Access Control Lists

Access Control Lists provides an additional, more flexible permission mechanism for file systems by allowing to set permissions for any user or group to any file.

Umask

The umask utility is used to control the file-creation mode mask, which determines the initial value of file permission bits for newly created files.

File attributes

Apart from the file mode bits that control user and group read, write and execute permissions, several file systems support file attributes that enable further customization of allowable file operations. This section describes some of these attributes and how to work with them.

Warning: By default, file attributes are not preserved by cp, rsync, and other similar programs.

chattr and lsattr

For ext2 and ext3 file systems, the e2fsprogs package contains the programs lsattr and chattr that list and change a file's attributes, respectively. Though some are not honored by all file systems, the available attributes are:

  • a: append only
  • c: compressed
  • d: no dump
  • e: extent format
  • i: immutable
  • j: data journalling
  • s: secure deletion
  • t: no tail-merging
  • u: undeletable
  • A: no atime updates
  • C: no copy on write
  • D: synchronous directory updates
  • S: synchronous updates
  • T: top of directory hierarchy

For example, if you want to set the immutable bit on some file, use the following command:

# chattr +i /path/to/file

To remove an attribute on a file just change + to -.

Extended attributes

From xattr(7): "Extended attributes are name:value pairs associated permanently with files and directories". There are four extended attribute classes: security, system, trusted and user.

Warning: By default, extended attributes are not preserved by cp, rsync, and other similar programs, see #Preserving extended attributes.

Extended attributes are also used to set Capabilities.

User extended attributes

User extended attributes can be used to store arbitrary information about a file. To create one:

$ setfattr -n user.checksum -v "3baf9ebce4c664ca8d9e5f6314fb47fb" foo.txt

Use getfattr to display extended attributes:

$ getfattr -d foo.txt
# file: foo.txt
user.checksum="3baf9ebce4c664ca8d9e5f6314fb47fb"

Finally, to remove an extended attribute:

$ setfattr -x user.checksum foo.txt

Preserving extended attributes

Command Required flag
cp --preserve=mode,ownership,timestamps,xattr
mv preserves by default1
tar --xattrs for creation and extraction
bsdtar -p for extraction
rsync --xattrs
  1. mv silently discards extended attributes when the target file system does not support them.

To preserve extended attributes with text editors you need to configure them to truncate files on saving instead of using rename(2).[1]

Tips and tricks

Preserve root

Use the --preserve-root flag to prevent chmod from acting recursively on /. This can, for example, prevent one from removing the executable bit systemwide and thus breaking the system. To use this flag every time, set it within an alias. See also [2].

See also