SELinux (Русский)

From ArchWiki
Jump to: navigation, search

Security-Enhanced Linux (SELinux) это функция Linux, которая обеспечивает множество политик безопасности, включая U.S. Обязательные средства управления доступом (MAC, Mandatory Access Controls) стиля министерства обороны, с помощью Linux Security Modules (LSM) в ядре Linux. Это не дистрибутив Linux, а скорее ряд модификаций, которые могут быть применены к Unix-подобным операционным системам, таким как Linux и BSD. Её архитектура стремится оптимизировать объем программного обеспечения, обвиненного в осуществлении политики безопасности, которое является близко выровненное Trusted Computer System Evaluation Criteria (TCSEC, называемый Оранжевой книгой) требование для минимизации достоверной вычислительной базы (TCB) (применимый к классам B3 и A1 оценки), но довольно не связано с наименьшим количеством требования полномочия (B2, B3, A1), как часто требуется. Зародышевые понятия базовый SELinux могут быть прослежены до нескольких более ранних проектов американским Агентством национальной безопасности (NSA). [1]

Для выполнения SELinux под дистрибутивом Linux требуется: включить SELinux в ядро, инструменты SELinux Userspace и библиотеки, и SELinux Policies (главным образом на основе Reference Policy). Некоторые общие программы Linux должны также исправляться/компилироваться с функциями SELinux.

Contents

Обязательные требования

Поддерживаются только файловые системы ext2, ext3, ext4, JFS и XFS.

Note: This is probably not needed anymore:

Пользователи XFS должны использовать 512 байтов inodes (значение по умолчанию 256). Использование SELinux расширяло атрибуты для того, чтобы сохранить метки безопасности в файлах. XFS хранит это в inode, и если inode слишком маленький, должен использоваться дополнительный блок, который тратит впустую много пространства и подвергается потерям производительности.

 # mkfs.xfs -i size=512 /dev/sda1  (for example)

Установка необходимых пакетов

Должны быть установлены по крайней мере linux-selinux, selinux-pam, selinux-usr-policycoreutils и selinux-refpolicy-src из AUR. Рекомендуется установить все пакеты, требуемые SELinux.

При установке из AUR (Русский), можете использовать AUR helper (Русский) или загружать tarballs из AUR вручную и собирать с makepkg. При замене пакетов pam и coreutils будьте особо внимательны, поскольку они жизненно важны для системы. Приготовьте Live CD или Live USB на случай, если придётся переустановить систему.


Warning: Установливая, например, selinux-pam пакетный менеджер (pacman) сообщит о конфликте и предложит удалить pam. Согласитесь и pacman сам удалит, и установит требуемые пакеты. При замене обращайте внимание на любые ошибки, если они будут.

Описание пакета

Все пакеты, принадлежащие к SELinux находятся в группе selinux. В selinux-userspace пакеты пользователтского пространства SELinux. В selinux-policies находятся пакеты политик SELinux. Остальные пакеты находятся в selinux-extras.

SELinux aware system utils

linux-selinux
Активирует поддержку SELinux ядром. Компиляция модулей подобно Virtualbox.
selinux-coreutils
Компиляция пакета coreutils с включенной поддержкой SELinux.
selinux-flex
Версия flex, необходимая только для сборки checkpolicy. Текущий flex имеет ошибку, вызывающую отказ в выполнении команды checkmodule.
selinux-pam
Пакет PAM с pam_selinux.so.
selinux-sysvinit
sysvinit загружает политики при старте системы. Будьте осторожны; если политика SELinux не сможет быть загружена это перестанет работать!
selinux-util-linux
Версия util-linux, скомпилированная с включенной поддержкой SELinux.
selinux-udev сделал устаревшим selinux-sysvinit
Версия udev, скомпилированная с включенной поддержкой SELinux для маркировки файлов в /dev для правильной работы. Функциональность udev теперь обеспечена selinux-sysvinit-tools [1], которая является частью selinux-sysvinit splitpackage.
selinux-findutils
Пропатченная версия findutils с активированной поддержкой SELinux, необходимая для поиска файлов в указанном возможном контексте безопасности.
selinux-sudo
Версия sudo с активированной поддержкой SELinux, для корректной устанавки контекста безопасности.
selinux-procps
Исправления пакета procps на основе некоторых патчей Fedora.
selinux-psmisc
Версия psmisc с активированной поддержкой SELinux. Добавляет опцию -Z к killall.
selinux-shadow
Версия shadow с активированной поддержкой SELinux. Содержит изменённый /etc/pam.d/login для корректной установки контекста безопасности после входа в систему.
selinux-cronie
Vixie cron из дистрибутива Fedora с активированной поддержкой SELinux.
selinux-logrotate
Версия logrotate с активированной поддержкой SELinux.
selinux-openssh
Версия OpenSSH с активированной поддержкой SELinux, для установки контекста безопасности в течение многих сеансов пользователя.

Пространство пользователя SELinux

selinux-usr-checkpolicy
Tools to build SELinux policy
selinux-usr-libselinux
Library for security-aware applications. Python bindings needed for semanage and setools now included.
selinux-usr-libsemanage
Library for policy management. Python bindings needed for semanage and setools now included.
selinux-usr-libsepol
Library for binary policy manipulation.
selinux-usr-policycoreutils
SELinux core utils such as newrole, setfiles, etc.
selinux-usr-sepolgen
A Python library for parsing and modifying policy source.

Политики SELinux

selinux-refpolicy
Precompiled modular-otherways-vanilla Reference policy with headers and documentation but without sources.
selinux-refpolicy-src
Reference policy sources
selinux-refpolicy-arch
Precompiled modular Reference policy with headers and documentation but without sources. Development Arch Linux Refpolicy patch included, but for now [February 2011] it only fixes some issues with /etc/rc.d/* labeling.

Другие утилиты SELinux

selinux-setools
CLI and GUI tools to manage SELinux
audit
User space utilities for storing and searching the audit records generated by the audit subsystem in the Linux kernel. SELinux (AVC) will log all denials using audit. Very useful in troubleshooting SELinux. Also audit2allow use log from this program.
Note: If using proprietary drivers, such as NVIDIA graphics drivers, you may need to rebuild them for custom kernels.

Configuration

После установки всех необходимых пакетов их необходимо настроить.

Changing boot loader configuration

Добавьте в конфигурационный файл GRUB /boot/grub/menu.lst следующие строки:

# (1) Arch Linux
title  Arch Linux (SELinux)
root   (hd0,0)
kernel vmlinuz-linux-selinux root=/dev/sda5 ro vga=775
initrd initramfs-linux-selinux.img

Mounting selinuxfs

Добавьте в /etc/fstab:

none   /selinux   selinuxfs   noauto   0   0

Создайте папку /selinux:

mkdir /selinux

Main SELinux configuration file

Основной конфигурационный файл SELLinux (/etc/selinux/config) является частью пакета selinux-refpolicy, доступного из AUR. Его содержимое по умолчанию:

# This file controls the state of SELinux on the system.
# SELINUX= can take one of these three values:
#       enforcing - SELinux security policy is enforced.
#       permissive - SELinux prints warnings 
#                       instead of enforcing.
#       disabled - No SELinux policy is loaded.
SELINUX=permissive
# SELINUXTYPE= takes the name of SELinux policy to
# be used. Current options are:
#       refpolicy (vanilla reference policy)
#       refpolicy-arch (reference policy with 
#       Arch Linux patch)
SELINUXTYPE=refpolicy
Note: Опция SELINUX=permissive подходит только для конфигурации. Это не увеличивает безопасность и после настройки измените её на SELINUX=enforcing. Опция SELINUXTYPE=refpolicy устанавливает имя используемой политики. Измените его на имя вашей политики. Если вы решили скомпилировать политику из исходников, вы должны самостоятельно создать файл.

Set up PAM

Correctly set-up PAM is important to get a proper security context after login. If you installed selinux-shadow from the AUR, there should be the following lines in /etc/pam.d/login:

# pam_selinux.so close should be the first session rule
session         required        pam_selinux.so close
# pam_selinux.so open should only be followed by sessions to be executed in the user context
session         required        pam_selinux.so open

If not, add them to the file. Similarly for logging in via SSH in /etc/pam.d/sshd, which is part of selinux-openssh package.

If you want to use SELinux with GUI, you should add the aforementioned lines to other files such as /etc/pam.d/kde, /etc/pam.d/kde-np, ... depending on your login manager.

Note: Running SELinux with GUI applications in Arch Linux is not much supported at the time being.

Reference policy

There are currently two possible ways of installing reference policy: From a pre-compiled package (selinux-refpolicy) or from a source package (selinux-refpolicy-src).

Note: It is possible to have both the source and the binary package installed. If you plan to build from source in that case, you should probably change the name of policy in build.conf to avoid overwriting of selinux-refpolicy package files.

Installing a precompiled refpolicy

Install selinux-refpolicy from AUR. This is a modular-otherways-vanilla refpolicy. This package includes policy headers (you can therefore compile your own modules), policy documentation and an install script which will load the policy for you and relabel your filesystem (which will likely take some time). It does not include the sources though.

This package also includes the main SELinux configuration file (/etc/selinux/config) defaulting to refpolicy and permissive SELinux enforcement for testing purposes.

You should verify that the policy was correctly loaded, that is if the file /etc/selinux/refpolicy/policy/policy.24 has non-zero size. If so and if you have installed selinux-sysvinit and other needed packages, you are ready to reboot and make sure that everything works.

Warning: On newer kernels (eg. 3.0) policy in file /etc/selinux/refpolicy/policy/policy.24 has zero bytes size, because it is used new version of policy from file: /etc/selinux/refpolicy/policy/policy.26

In case the policy was not correctly loaded you can as root use the following command inside of the /usr/share/selinux/refpolicy directory to do so:

/bin/ls *.pp | /bin/grep -Ev "base.pp|enableaudit.pp" | /usr/bin/xargs /usr/sbin/semodule -s refpolicy -b base.pp -i

To manually relabel your filesystem you can as root use:

/sbin/restorecon -r /

Installing refpolicy from a source package

Install selinux-refpolicy-src from AUR. Edit the file /etc/selinux/refpolicy/src/policy/build.conf to your liking.

Note: Build configuration file build.conf is overwritten on every selinux-refpolicy-src package upgrade, so backup your configuration.

To build, install and load policy from source do the following. (For other possibilities consult the README file located in /etc/selinux/refpolicy/src/policy/.)

cd /etc/selinux/refpolicy/src/policy
make bare
make conf 
make load

Copy or link the compiled binary policy to /etc/policy.bin for sysvinit to find and install selinux-sysvinit:

ln -s /etc/selinux/refpolicy/policy/policy.21 /etc/policy.bin

At this moment files do not have any context, so you should relabel the whole filesystem, which will take a while:

make relabel

Create the main SELinux configuration file (/etc/selinux/config) according to the example in related section.

Now you are ready to reboot and make sure that everything works.

Post-installation steps

Warning: Если selinux-sysvinit не установлен, то SELinux не сможет запуститься и /selinux не будет смонтирован.

Выполните sestatus чтобы убедиться, что SELinux работает. Должно получиться что-то вроде этого:

SELinux status:                 enabled
SELinuxfs mount:                /selinux
Current mode:                   permissive
Mode from config file:          permissive
Policy version:                 26
Policy from config file:        refpolicy

To maintain correct context, you can use restorecond:

touch /etc/rc.d/restorecond
chmod ugo+x /etc/rc.d/restorecond

Which should contain:

#!/bin/sh
restorecond
Note: Не забудьте добавить restorecond в список DAEMONS вашего /etc/rc.conf.

Чтобы переключиться на осуществление режима без перезагрузки, можете использовать:

echo 1 > /selinux/enforce
Note: Если SELINUX=enforcing в /etc/selinux/config не работает, создайте /etc/rc.d/selinux-enforce содержащий предыдущую команду так же как с restorecond демоном.

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
rlpkg
Relabels any files belonging to that Gentoo package to their proper security context (if they have one)
chcon
Change the context on a specific file
audit2allow
Reads in log messages from the AVC log file and tells you what rules would fix the error. Do not just add these rules without looking at them though, they cannot detect errors in other places (e.g. the application is running in the wrong context in the first place), or sometimes things will generate error messages but may maintain functionality so it would be better to add dontaudit to just ignore the access attempts.

References

See also

  • AppArmor (Similar to SELinux, much easier to configure, less features.)