What is access control list in linux

Sysadminium

В этой статье разберём расширенные права доступа к файлам в Linux, которые называются Access Control List / списки контроля доступа (ACL).

О системе прав ACL в Linux

В этой статье мы познакомились со стандартной системой прав в Linux. Но может возникнуть ситуация, что к файлу с правами: rw-r—r— user1 user1 , нужно дать доступ пользователю admin с правами rw- , и пользователю user2 c правами r— .

Стандартная система прав здесь не поможет. Для решения подобной задачи применяют ACL (Access Control List / списки контроля доступа).

  • права доступа к файлу — определяет доступ к файлу или каталогу;
  • ACL default — назначается только каталогу, при этом создаваемые файлы в этом каталоге будут наследовать такие права.

Подготовка системы к практике

Давайте для начала создадим трёх новых пользователей в системе. Так как это административное действие то в Ubuntu я использую sudo, а в Debian переключусь на пользователя root:

alex@ubu:~$ sudo useradd -m -s /bin/bash admin alex@ubu:~$ sudo useradd -m -s /bin/bash user1 alex@ubu:~$ sudo useradd -m -s /bin/bash user2 alex@deb:~$ su - Пароль: root@deb:~# useradd -m -s /bin/bash admin root@deb:~# useradd -m -s /bin/bash user1 root@deb:~# useradd -m -s /bin/bash user2

Про создание пользователей я писал в этой статье.

Установим пользователям пароли:

alex@ubu:~$ sudo passwd admin New password: Retype new password: passwd: password updated successfully alex@ubu:~$ sudo passwd user1 New password: Retype new password: passwd: password updated successfully alex@ubu:~$ sudo passwd user2 New password: Retype new password: passwd: password updated successfully root@deb:~# passwd admin Новый пароль: Повторите ввод нового пароля: passwd: пароль успешно обновлён root@deb:~# passwd user1 Новый пароль: Повторите ввод нового пароля: passwd: пароль успешно обновлён root@deb:~# passwd user2 Новый пароль: Повторите ввод нового пароля: passwd: пароль успешно обновлён

Дальше все примеры для Ubuntu я показывать не буду, там всё аналогично. Единственное не забывайте при административных действиях использовать sudo перед командами.

Под пользователем user1 создадим каталог test и в нем файл file1.txt:

root@deb:~# su - user1 user1@deb:~$ mkdir test user1@deb:~$ touch test/file1.txt user1@deb:~$ exit выход root@deb:~#

На этом подготовка системы закончена, мы сделали трёх пользователей: admin, user1 и user2. И в домашнем каталоге пользователя user1 создали каталог test в котором создали файл file1.txt.

Работа с ACL в Linux

Для начала установим систему acl, про установку дополнительных пакетов в систему поговорим позже, просто выполните:

Чтобы посмотреть acl права на файл или каталог используют команду getfacl (её может выполнить любой пользователь без административных прав):

root@deb:~# getfacl /home/user1/test/file1.txt getfacl: Removing leading '/' from absolute path names # file: home/user1/test/file1.txt # owner: user1 # group: user1 user::rw- group::r-- other::r--

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

Читайте также:  Kali linux window themes

Для установки acl прав используем команду setfacl (выполнять эту команду может только root пользователь, или пользователь с sudo правами):

  • опция -m используется когда нужно модифицировать права;
  • дальше, если мы устанавливаем права для пользователя, то ставим символ u, для группы будем использовать символ g;
  • затем, после двоеточия, имя пользователя;
  • дальше, после двоеточия, права доступа для этого пользователя;
  • и наконец указываем имя файла.

Вот примерное использование setfacl:

# setfacl -m u:пользователь:права_доступа файл # setfacl -m g:группа:права_доступа файл

Вот как решается описанная в самом начале задача, используя acl:

root@deb:~# setfacl -m u:admin:rw-,u:user2:r-- /home/user1/test/file1.txt root@deb:~# getfacl /home/user1/test/file1.txt getfacl: Removing leading '/' from absolute path names # file: home/user1/test/file1.txt # owner: user1 # group: user1 user::rw- user:admin:rw- user:user2:r-- group::r-- mask::rw- other::r--

При этом если мы посмотрим командой ls -l права, то заметим знак «+«, который и указывает что файл имеет дополнительные acl права:

root@deb:~# ls -l /home/user1/test/file1.txt -rw-rw-r--+ 1 user1 user1 0 янв 20 14:38 /home/user1/test/file1.txt

Для группы владельцев и всех остальных также можно устанавливать acl права таким образом:

setfacl -m g:groupname:rwx setfacl -m o:rwx

Для того чтобы удалить пользователя или группу из acl нужно использовать команду setfacl с опцией -x, например вот так:

root@deb:~# setfacl -x u:user2 /home/user1/test/file1.txt root@deb:~# getfacl /home/user1/test/file1.txt getfacl: Removing leading '/' from absolute path names # file: home/user1/test/file1.txt # owner: user1 # group: user1 user::rw- user:admin:rw- group::r-- mask::rw- other::r--

Как видим у пользователя user2 не осталось acl прав к этому файлу. Таким же образом можем удалить группу:

Для того чтобы удалить все acl права с файла используем команду setfacl с опцией -b:

root@deb:~# setfacl -b /home/user1/test/file1.txt root@deb:~# getfacl /home/user1/test/file1.txt getfacl: Removing leading '/' from absolute path names # file: home/user1/test/file1.txt # owner: user1 # group: user1 user::rw- group::r-- other::r--

Наследование ACL

Теперь разберемся с acl default. Устанавливаются такие права только на каталог. Для установки таких прав используется команда setfacl с опцией -d:

root@deb:~# setfacl -d -m u::rwx,g::rw-,o::r,u:admin:rw /home/user1/test/ root@deb:~# getfacl /home/user1/test/ getfacl: Removing leading '/' from absolute path names # file: home/user1/test/ # owner: user1 # group: user1 user::rwx group::r-x other::r-x default:user::rwx default:user:admin:rw- default:group::rw- default:mask::rw- default:other::r--

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

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

root@deb:~# touch /home/user1/test/file2.txt root@deb:~# getfacl /home/user1/test/file2.txt getfacl: Removing leading '/' from absolute path names # file: home/user1/test/file2.txt # owner: root # group: root user::rw- user:admin:rw- group::rw- mask::rw- other::r--

Выше я создал файл из под пользователя root, но пользователь admin получил к нему доступ, так как он указан в правах default этого каталога.

Маска ACL

Кроме прав доступа и прав по умолчанию в acl присутствуем маска. Маска говорит о максимально возможных назначенных правах для пользователей. Она вычисляется автоматически при добавлении пользователя. Т.е. мы можем одному пользователю дать права rw- , второму r— , маска при этом станет rw- .

Маску можно изменить командой setfacl -m m:права_доступа файл например:

root@deb:~# touch /home/user1/test/file2.txt root@deb:~# setfacl -m m:r /home/user1/test/file2.txt root@deb:~# getfacl /home/user1/test/file2.txt getfacl: Removing leading '/' from absolute path names # file: home/user1/test/file2.txt # owner: root # group: root user::rw- user:admin:rw- #effective:r-- group::rw- #effective:r-- mask::r-- other::r--

По значению effective:r— мы видим что права изменились.

Читайте также:  High availability clustering linux

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

Рекурсивное назначение прав

Для установки рекурсивно прав на все файлы в каталоге и подкаталогах используется опция -R, её же можно использовать при удалении прав:

setfacl -R -m u:пользователь:права_доступа каталог setfacl -R -b каталог

Источник

Access Control Lists

Access control list (ACL) provides an additional, more flexible permission mechanism for file systems. It is designed to assist with UNIX file permissions. ACL allows you to give permissions for any user or group to any disk resource.

Installation

The acl package is a dependency of systemd, it should already be installed.

Enable ACL

To enable ACL, the filesystem must be mounted with the acl option. You can use fstab entries to make it permanent on your system.

There is a possibility that the acl option is already active as one of the default mount options on the filesystem. Btrfs and Ext2/3/4 filesystems are affected by this. Use the following command to check ext2/3/4 formatted partitions for the option:

# tune2fs -l /dev/sdXY | grep "Default mount options:"
Default mount options: user_xattr acl 

Also check that the default mount options are not overridden, in such case you will see noacl in /proc/mounts in the relevant line.

You can set the default mount options of a filesystem using the tune2fs -o option partition command, for example:

# tune2fs -o acl /dev/sdXY 

Using the default mount options instead of an entry in /etc/fstab is very useful for external drives, such partition will be mounted with acl option also on other Linux machines. There is no need to edit /etc/fstab on every machine.

  • acl is specified as a default mount option when creating an ext2/3/4 filesystem. This is configured in /etc/mke2fs.conf .
  • The default mount options are not listed in /proc/mounts .

Usage

Set ACL

The ACL can be modified using the setfacl command.

  • You can list file/directory permission changes without modifying the permissions (i.e. dry-run) by appending the —test flag.
  • To apply operations to all files and directories recursively, append the -R / —recursive argument.

To set permissions for a user ( user is either the user name or ID):

# setfacl -m "u:user:permissions" 

To set permissions for a group ( group is either the group name or ID):

# setfacl -m "g:group:permissions" 

To set permissions for others:

# setfacl -m "other:permissions" 

To allow all newly created files or directories to inherit entries from the parent directory (this will not affect files which will be copied into the directory):

To remove a specific entry:

To remove the default entries:

Читайте также:  Приказ мвд astra linux

To remove all entries (entries of the owner, group and others are retained):

The factual accuracy of this article or section is disputed.

Reason: The original note about the —mask option (which was taken from setfacl(1) ) was determined as inaccurate, but the new note does not seem correct either. See the talk page for details. (Discuss in Talk:Access Control Lists#ACL mask entry)

Note: The default behavior of setfacl is to recalculate the ACL mask entry, unless a —mask entry was explicitly given. The mask entry indicates the maximum permissions allowed for users (other than the owner) and for groups. Unless explicitly set, this will match the permissions of the default group. To clarify what this means, suppose the group owning a directory has r-x permissions. If you add an ACL user or group with rwx permissions, the effective permissions of this user or group will be r-x . The reason for this is so that there are no surprises when a file from a system which does not support ACLs is made available on a system which does..

Show ACL

Examples

Set all permissions for user johnny to file named abc :

# file: abc # owner: someone # group: someone user::rw- user:johnny:rwx group::r-- mask::rwx other::r--

Change permissions for user johnny :

# file: abc # owner: someone # group: someone user::rw- user:johnny:r-x group::r-- mask::r-x other::r--
# file: abc # owner: someone # group: someone user::rw- group::r-- other::r--

Output of ls command

You will notice that there is an ACL for a given file because it will exhibit a + (plus sign) after its Unix permissions in the output of ls -l .

crw-rw----+ 1 root audio 14, 4 nov. 9 12:49 /dev/audio
getfacl: Removing leading '/' from absolute path names # file: dev/audio # owner: root # group: audio user::rw- user:solstice:rw- group::rw- mask::rw- other::---

Execution permissions for private files

The following technique describes how a process like a web server can be granted access to files that reside in a user’s home directory, without compromising security by giving the whole world access.

In the following we assume that the web server runs as the user http and grant it access to geoffrey ‘s home directory /home/geoffrey .

The first step is granting execution permissions for the user http :

# setfacl -m "u:http:--x" /home/geoffrey

Note: Execution permissions to a directory are necessary for a process to list the directory’s content.

Since the user http is now able to access files in /home/geoffrey , others no longer need access:

Use getfacl to verify the changes:

getfacl: Removing leading '/' from absolute path names # file: home/geoffrey # owner: geoffrey # group: geoffrey user::rwx user:http:--x group::r-x mask::r-x other::---

As the above output shows, other ‘s no longer have any permissions, but the user http is still able to access the files, thus security might be considered increased.

If you need to give write access for the user http on specific directories and/or files, run:

# setfacl -dm "u:http:rwx" /home/geoffrey/project1/cache

See also

Источник

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