- SELinux
- Contents
- Current status in Arch Linux
- Concepts: Mandatory Access Controls
- Installing SELinux
- Package description
- SELinux aware system utilities
- SELinux userspace utilities
- SELinux policy packages
- Other SELinux tools
- Installation
- Via AUR
- Using the GitHub repository
- Enable SELinux LSM
- Custom kernel
- Checking PAM
- Installing a policy
- Testing in a Vagrant virtual machine
- Post-installation steps
- Swapfiles
- Working with SELinux
- Troubleshooting
- Useful tools
- Руководство для начинающих по SELinux
- Изменение режимов SELinux
- Настройка SELinux
- Мониторим логи
- Настройка политики SELinux
- 1. Логические значения (переключатели)
- 2. Метки и контекст
- 3. Создание локальных политик
SELinux
Security-Enhanced Linux (SELinux) is a Linux feature that provides a variety of security policies, including U.S. Department of Defense style Mandatory Access Control (MAC), through the use of Linux Security Modules (LSM) in the Linux kernel. It is not a Linux distribution, but rather a set of modifications that can be applied to Unix-like operating systems, such as Linux and BSD.
Running SELinux under a Linux distribution requires three things: An SELinux enabled kernel, SELinux Userspace tools and libraries, and SELinux Policies (mostly based on the Reference Policy). Some common Linux programs will also need to be patched/compiled with SELinux features.
Contents
Current status in Arch Linux
SELinux is not officially supported (see [1][2]). The status of unofficial support is:
Name | Status | Available at |
---|---|---|
SELinux enabled kernel | Implemented for all officially supported kernels | Available in official repositories since 4.18.8. |
SELinux Userspace tools and libraries | Implemented in AUR: https://aur.archlinux.org/packages/?O=0&K=selinux | Work is done at https://github.com/archlinuxhardened/selinux |
SELinux Policy | Work in progress, using Reference Policy as upstream | Upstream: https://github.com/SELinuxProject/refpolicy (since release 20170805 the policy has integrated support for systemd and single-/usr/bin directory) |
Summary of changes in AUR as compared to official core packages:
Name | Status and comments |
---|---|
linux, linux-lts, linux-zen, linux-hardened | Need to set the lsm= kernel parameter |
coreutils | Need a rebuild with —with-selinux flag to link with libselinux |
cronie | Need a rebuild with —with-selinux flag |
dbus | Need a rebuild with —enable-libaudit and —enable-selinux flags |
findutils | Need a rebuild with libselinux installed to enable SELinux-specific options |
iproute2 | Need a rebuild with —with-selinux flag |
logrotate | Need a rebuild with —with-selinux flag |
openssh | Need a rebuild with —with-selinux flag |
pam | Need a rebuild with —enable-selinux flag for Linux-PAM ; Need a patch for pam_unix2, which only removes a function already implemented in a recent versions of libselinux |
pambase | Configuration changes to add pam_selinux.so to /etc/pam.d/system-login |
psmisc | Need a rebuild with —with-selinux flag |
shadow | Need a rebuild with —with-selinux flags |
sudo | Need a rebuild with —with-selinux flag |
systemd | Need a rebuild with —enable-audit and —enable-selinux flags |
util-linux | Need a rebuild with —with-selinux flag |
All of the other SELinux-related packages may be included without changes nor risks.
Concepts: Mandatory Access Controls
Before you enable SELinux, it is worth understanding what it does. Simply and succinctly, SELinux enforces Mandatory Access Controls (MACs) on Linux. In contrast to SELinux, the traditional user/group/rwx permissions are a form of Discretionary Access Control (DAC). MACs are different from DACs because security policy and its execution are completely separated.
An example would be the use of the sudo command. When DACs are enforced, sudo allows temporary privilege escalation to root, giving the process so spawned unrestricted systemwide access. However, when using MACs, if the security administrator deems the process to have access only to a certain set of files, then no matter what the kind of privilege escalation used, unless the security policy itself is changed, the process will remain constrained to simply that set of files. So if sudo is tried on a machine with SELinux running in order for a process to gain access to files its policy does not allow, it will fail.
Another set of examples are the traditional (-rwxr-xr-x) type permissions given to files. When under DAC, these are user-modifiable. However, under MAC, a security administrator can choose to freeze the permissions of a certain file by which it would become impossible for any user to change these permissions until the policy regarding that file is changed.
As you may imagine, this is particularly useful for processes which have the potential to be compromised, i.e. web servers and the like. If DACs are used, then there is a particularly good chance of havoc being wreaked by a compromised program which has access to privilege escalation.
Installing SELinux
Package description
All SELinux related packages belong to the selinux group in the AUR.
SELinux aware system utilities
SELinux userspace utilities
SELinux policy packages
Other SELinux tools
Installation
There are two methods to install the requisite SELinux packages.
Via AUR
- First, install SELinux userspace tools and libraries, in this order (because of the dependencies): libsepolAUR , libselinuxAUR , checkpolicyAUR , secilcAUR , setoolsAUR , libsemanageAUR , semodule-utilsAUR , policycoreutilsAUR , selinux-pythonAUR (which depends on python-ipy ), mcstransAUR and restorecondAUR .
- Then install pambase-selinuxAUR and pam-selinuxAUR and make sure you can login again after the installation completed, because files in /etc/pam.d/ got removed and created when pambase got replaced with pambase-selinuxAUR .
- Next you can recompile some core packages by installing: coreutils-selinuxAUR , findutils-selinuxAUR , iproute2-selinuxAUR , logrotate-selinuxAUR , openssh-selinuxAUR , psmisc-selinuxAUR , shadow-selinuxAUR , cronie-selinuxAUR
- Next, backup your /etc/sudoers file. Install sudo-selinuxAUR and restore your /etc/sudoers (it is overridden when this package is installed as a replacement of sudo ).
- Next come util-linux and systemd. Because of a cyclic makedepends between these two packages which will not be fixed (FS#39767), you need to build the source package systemd-selinuxAUR , install systemd-libs-selinuxAUR , build and install util-linux-selinuxAUR (with util-linux-libs-selinuxAUR ) and rebuild and install systemd-selinuxAUR .
- Next, install dbus-selinuxAUR .
- Next, install selinux-alpm-hookAUR in order to run restorecon every time pacman installs a package.
After all these steps, you can install a SELinux kernel (like linux ) and a policy (like selinux-refpolicy-arch AUR or selinux-refpolicy-git AUR ).
Using the GitHub repository
All packages are maintained at https://github.com/archlinuxhardened/selinux . This repository also contains a script named build_and_install_all.sh which builds and installs (or updates) all packages in the needed order. Here is an example of a way this script can be used in a user shell to install all packages (with downloading the GPG keys which are used to verify the source tarballs of the package):
Of course, it is possible to modify the content of build_and_install_all.sh before running it, for example if you already have SELinux support in your kernel.
Enable SELinux LSM
To enable SELinux as default security model on every boot, set the following kernel parameter:
Custom kernel
When compiling the kernel, it is required to set at least the following options:
To enable the SELinux Linux security model by default and omit the need to set kernel parameters, additionally set the CONFIG_LSM option and specify selinux as the first «major» module in the list:
Checking PAM
A correctly set-up PAM is important to get the proper security context after login. Check for the presence of the following lines in /etc/pam.d/system-login :
Installing a policy
Policies are the mainstay of SELinux. They are what govern its behaviour. The only policy currently available in the AUR is the Reference Policy. In order to install it, you should use the source files, which may be got from the package selinux-refpolicy-src AUR or by downloading the latest release on https://github.com/SELinuxProject/refpolicy/wiki/DownloadRelease#current-release. When using the AUR package, navigate to /etc/selinux/refpolicy/src/policy and run the following commands:
to install the reference policy as it is. Those who know how to write SELinux policies can tweak them to their heart’s content before running the commands written above. The command takes a while to do its job and taxes one core of your system completely, so do not worry. Just sit back and let the command run for as long as it takes.
To load the reference policy run:
Then, make the file /etc/selinux/config with the following contents (Only works if you used the defaults as mentioned above. If you decided to change the name of the policy, you need to tweak the file):
Now, you may reboot. After rebooting, run:
to label your filesystem.
Now, make a file requiredmod.te with the contents:
and run the following commands:
This is required to remove a few messages from /var/log/audit/audit.log which are a nuisance to deal with in the reference policy. This is an ugly hack and it should be made very clear that the policy so installed simply patches the reference policy in order to hide the effects of incorrect labelling.
Testing in a Vagrant virtual machine
It is possible to use Vagrant to provision a virtual Arch Linux machine with SELinux configured. This is a convenient way to test an Arch Linux system running SELinux without modifying a current system. Here are commands which can be used to achieve this:
Post-installation steps
You can check that SELinux is working with sestatus . You should get something like:
To maintain correct context, you can enable restorecond.service .
To switch to enforcing mode without rebooting, you can use:
Swapfiles
If you have a swap file instead of a swap partition, issue the following commands in order to set the appropriate security context:
Working with SELinux
SELinux defines security using a different mechanism than traditional Unix access controls. The best way to understand it is by example. For example, the SELinux security context of the apache homepage looks like the following:
The first three and the last columns should be familiar to any (Arch) Linux user. The fourth column is new and has the format:
- User: The SELinux user identity. This can be associated to one or more roles that the SELinux user is allowed to use.
- Role: The SELinux role. This can be associated to one or more types the SELinux user is allowed to access.
- Type: When a type is associated with a process, it defines what processes (or domains) the SELinux user (the subject) can access. When a type is associated with an object, it defines what access permissions the SELinux user has to that object.
- Level: This optional field can also be know as a range and is only present if the policy supports MCS or MLS.
This is important in case you wish to understand how to build your own policies, for these are the basic building blocks of SELinux. However, for most purposes, there is no need to, for the reference policy is sufficiently mature. However, if you are a power user or someone with very specific needs, then it might be ideal for you to learn how to make your own SELinux policies.
This [dead link 2021-07-12 ⓘ] is a great series of articles for someone seeking to understand how to work with SELinux.
Troubleshooting
The place to look for SELinux errors is the systemd journal. In order to see SELinux messages related to the label system_u:system_r:policykit_t:s0 (for example), you would need to run:
Useful tools
There are some tools/commands that can greatly help with SELinux.
restorecon Restores the context of a file/directory (or recursively with -R ) based on any policy rules chcon Change the context on a specific file
Источник
Руководство для начинающих по SELinux
Перевод статьи подготовлен для студентов курса «Безопасность Linux»
SELinux или Security Enhanced Linux — это улучшенный механизм управления доступом, разработанный Агентством национальной безопасности США (АНБ США) для предотвращения злонамеренных вторжений. Он реализует принудительную (или мандатную) модель управления доступом (англ. Mandatory Access Control, MAC) поверх существующей дискреционной (или избирательной) модели (англ. Discretionary Access Control, DAC), то есть разрешений на чтение, запись, выполнение.
У SELinux есть три режима:
- Enforcing — запрет доступа на основании правил политики.
- Permissive — ведение лога действий, нарушающих политику, которые в режиме enforcing были бы запрещены.
- Disabled — полное отключение SELinux.
По умолчанию настройки находятся в /etc/selinux/config
Изменение режимов SELinux
Чтобы узнать текущий режим запустите
Для изменения режима на permissive запустите следующую команду
или, для изменения режима с permissive на enforcing, выполните
Если вам нужно полностью отключить SELinux, то это можно сделать только через файл конфигурации
Для отключения измените параметр SELINUX следующим образом:
Настройка SELinux
Каждый файл и процесс помечается контекстом SELinux, в котором содержится дополнительная информация, такая как пользователь, роль, тип и т.д. Если вы впервые включаете SELinux, то сначала нужно настроить контекст и метки. Процесс назначения меток и контекста известен как маркировка. Чтобы начать маркировку, в файле конфигурации изменим режим на permissive.
После установки режима permissive, создадим в корне пустой скрытый файл с именем autorelabel
и перезагрузим компьютер
Примечание: мы используем режим permissive для маркировки, поскольку использование режима enforcing может привести к краху системы во время перезагрузки.
Не беспокойтесь, если загрузка застрянет на каком-то файле, маркировка занимает некоторое время. После завершения маркировки и загрузки вашей системы вы можете перейти к файлу конфигурации и установить режим enforcing, а также запустить:
Теперь вы успешно включили SELinux на своем компьютере.
Мониторим логи
Возможно, у вас возникли какие-то ошибки во время маркировки или во время работы системы. Чтобы проверить, работает ли ваш SELinux правильно и не блокирует ли он доступ к какому-либо порту, приложению и т. д. нужно посмотреть логи. Лог SELinux находится в /var/log/audit/audit.log , но вам не нужно читать его целиком, чтобы найти ошибки. Можно использовать утилиту audit2why для поиска ошибок. Запустите следующую команду:
В результате вы получите список ошибок. Если ошибок в логе не было, то никаких сообщений отображаться не будет.
Настройка политики SELinux
Политика SELinux — это набор правил, которыми руководствуется механизм безопасности SELinux. Политика определяет набор правил для конкретного окружения. Сейчас мы изучим как настраивать политики, чтобы разрешить доступ к запрещенным сервисам.
1. Логические значения (переключатели)
Переключатели (booleans) позволяют изменять части политики во время работы, без необходимости создания новых политик. Они позволяют вносить изменения без перезагрузки или перекомпиляции политик SELinux.
Пример
Предположим, мы хотим предоставить общий доступ к домашнему каталогу пользователя по FTP на чтение и запись, и мы уже расшарили его, но при попытке доступа мы ничего не видим. Это связано с тем, что политика SELinux запрещает FTP-серверу читать и писать в домашнем каталоге пользователя. Нам нужно изменить политику, чтобы FTP-сервер мог обращаться к домашним каталогам. Посмотрим, есть ли для этого какие-либо переключатели, выполнив
Эта команда выдаст список доступных переключателей с их текущим состоянием (включено/on или выключено/off) и описанием. Вы можете уточнить поиск, добавив grep, чтобы найти результаты, относящиеся только с ftp:
и найдете следующее
Этот переключатель выключен, поэтому мы включим его с помощью setsebool $ setsebool ftp_home_dir on
Теперь наш ftp-демон сможет получить доступ к домашнему каталогу пользователя.
Примечание: вы также можете получить список доступных переключателей без описания, выполнив getsebool -a
2. Метки и контекст
Это наиболее распространенный способ реализации политики SELinux. Каждый файл, папка, процесс и порт помечаются контекстом SELinux:
- Для файлов и папок метки хранятся как расширенные атрибуты в файловой системе и могут быть просмотрены следующей командой:
- Для процессов и портов маркировкой управляет ядро, и можно посмотреть эти метки следующим образом:
Пример
Теперь давайте рассмотрим пример, чтобы лучше понять метки и контекст. Допустим, у нас есть веб-сервер, который вместо каталога /var/www/html/ использует /home/dan/html/ . SELinux сочтет это нарушением политики, и вы не сможете просматривать ваши веб-страницы. Это потому, что мы не установили контекст безопасности, связанный с HTML-файлами. Для просмотра контекста безопасности по умолчанию используйте следующую команду:
Здесь мы получили httpd_sys_content_t в качестве контекста для html-файлов. Нам нужно установить этот контекст безопасности для нашего текущего каталога, который сейчас имеет следующий контекст:
Альтернативная команда для проверки контекста безопасности файла или каталога:
Мы также будем использовать semanage для изменения контекста, после того как найдем правильный контекст безопасности. Чтобы изменить контекст /home/dan/html, выполните следующие команды:
После того, как контекст изменен с помощью semanage, команда restorecon загрузит контекст по умолчанию для файлов и каталогов. Наш веб-сервер теперь сможет читать файлы из папки /home/dan/html , поскольку контекст безопасности для этой папки был изменен на httpd_sys_content_t .
3. Создание локальных политик
Могут возникнуть ситуации, когда вышеуказанные методы бесполезны для вас, и вы получаете ошибки (avc/denial) в audit.log. Когда такое происходит, то нужно создать локальную политику (Local policy). Все ошибки вы можете найти с помощью audit2why, как было описано выше.
Для устранения ошибок можно создать локальную политику. Например, мы получаем ошибку, связанную с httpd (apache) или smbd (samba), мы grep’аем ошибки и создаем для них политику:
Здесь http_policy и smb_policy — это названия локальных политик, которые мы создали. Теперь нам нужно загрузить эти созданные локальные политики в текущую политику SELinux. Это можно сделать следующим образом:
Наши локальные политики были загружены, и мы не должны больше получать никаких avc или denail в audit.log.
Это была моя попытка помочь вам понять SELinux. Я надеюсь, что после прочтения этой статьи вы будете чувствовать себя с SELinux более комфортно.
Источник