SELinuxservice — различия между версиями
Andy (обсуждение | вклад) (→Конфигурирование SELinux для поддерки сервиса) |
Andy (обсуждение | вклад) |
||
| (не показаны 32 промежуточные версии этого же участника) | |||
| Строка 1: | Строка 1: | ||
| − | == Конфигурирование SELinux для | + | == Конфигурирование SELinux для поддержки сервиса == |
==== Предварительные требования ==== | ==== Предварительные требования ==== | ||
| Строка 5: | Строка 5: | ||
* Установленные пакеты: <code>bash-completion</code>, <code>policycoreutils</code>, <code>policycoreutils-python</code>, <code>policycoreutils-devel</code>, <code>setroubleshoot-server</code> | * Установленные пакеты: <code>bash-completion</code>, <code>policycoreutils</code>, <code>policycoreutils-python</code>, <code>policycoreutils-devel</code>, <code>setroubleshoot-server</code> | ||
| − | ==== | + | == Общая информация == |
| + | <code>SELinux</code> представляет собой систему принудительного контроля доступа и позволяет разделить | ||
| + | пользовательские данные от сервисов которые были скомпрометированы. <code>SELinux</code> позволяет | ||
| + | определить какой процесс, к каким сущностям (файлы, директории, порты, процессы, пользователи) может иметь доступ. Уровень доступа к сущностям | ||
| + | носит название <code>контекст</code>. Терминология <code>SELinux</code>: | ||
| + | |||
| + | {| class="wikitable" | ||
| + | |- | ||
| + | ! Название элемента !! Описание | ||
| + | |- | ||
| + | | Policy || Набор правил, определяющих какой источник может иметь доступ к какой цели | ||
| + | |- | ||
| + | | Source domain || Объект, пытающийся получить доступ к цели. Обычно пользователь или процесс | ||
| + | |- | ||
| + | | Target domain || Сущность, к которой пытается получить доступ источник. Обычно файл или порт | ||
| + | |- | ||
| + | | Context || Метка безопасности, использующаяся для классификации объектов в SELinux | ||
| + | |- | ||
| + | | Rule || Конкретная часть политики, которая определяет какой источник имеет какие правила доступа к какой цели. | ||
| + | |- | ||
| + | | Lables || Тоже самое, что и контекст, определяет какой источник имеет какие правила доступа к какой цели. | ||
| + | |} | ||
| + | В системе <code>SELinux</code> может находится в 3 состояниях:<br/> | ||
| + | <code>enforcing</code> - Политики <code>SELinux</code> включены и применяются.<br/> | ||
| + | <code>permissive</code> - Политики <code>SELinux</code> включены, однако, вместо их применения, печатаются предупреждения. Данное поведение рекомендовано для отладки и поиска ошибок в файле <code>/var/log/audit/audit.log</code><br/> | ||
| + | <code>disabled</code> - Политики <code>SELinux</code> не применяются. Не рекомендовано к использованию, ибо ведет к несдаче экзамена.<br/> | ||
| + | Данные настройки можно внести в конфигурационный файл <code>/etc/sysconfig/selinux</code>: | ||
| + | <syntaxhighlight lang="bash"> | ||
| + | # 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=enforcing | ||
| + | # SELINUXTYPE= can take one of these two values: | ||
| + | # targeted - Targeted processes are protected, | ||
| + | # minimum - Modification of targeted policy. Only selected processes are protected. | ||
| + | # mls - Multi Level Security protection. | ||
| + | SELINUXTYPE=targeted | ||
| + | </syntaxhighlight> | ||
| + | При условии работоспособности <code>SELinux</code>, в командной строке его можно переключать между режимами <code>enforcing</code> и <code>permissive</code> при помощи команд <code>getenforce</code>/<code>setenforce</code>. Например:<br/> | ||
| + | <syntaxhighlight lang="bash"> | ||
| + | [root@vm-02 ~]# getenforce | ||
| + | Enforcing | ||
| + | [root@vm-02 ~]# setenforce 0 | ||
| + | [root@vm-02 ~]# getenforce | ||
| + | Permissive | ||
| + | [root@vm-02 ~]# setenforce 1 | ||
| + | [root@vm-02 ~]# getenforce | ||
| + | Enforcing | ||
| + | [root@vm-02 ~]# | ||
| + | </syntaxhighlight> | ||
| + | Так же, информацию о работоспособности <code>SELinux</code> и загруженных политиках, можно получить при помощи команды <code>sestatus</code>: | ||
| + | <syntaxhighlight lang="bash"> | ||
| + | [root@vm-02 ~]# sestatus -v | ||
| + | SELinux status: enabled | ||
| + | SELinuxfs mount: /sys/fs/selinux | ||
| + | SELinux root directory: /etc/selinux | ||
| + | Loaded policy name: targeted | ||
| + | Current mode: enforcing | ||
| + | Mode from config file: enforcing | ||
| + | Policy MLS status: enabled | ||
| + | Policy deny_unknown status: allowed | ||
| + | Max kernel policy version: 28 | ||
| + | |||
| + | Process contexts: | ||
| + | Current context: unconfined_u:unconfined_r:unconfined_t:s0-s0:c0.c1023 | ||
| + | Init context: system_u:system_r:init_t:s0 | ||
| + | /usr/sbin/sshd system_u:system_r:sshd_t:s0-s0:c0.c1023 | ||
| + | |||
| + | File contexts: | ||
| + | Controlling terminal: unconfined_u:object_r:user_devpts_t:s0 | ||
| + | /etc/passwd system_u:object_r:passwd_file_t:s0 | ||
| + | /etc/shadow system_u:object_r:shadow_t:s0 | ||
| + | /bin/bash system_u:object_r:shell_exec_t:s0 | ||
| + | /bin/login system_u:object_r:login_exec_t:s0 | ||
| + | /bin/sh system_u:object_r:bin_t:s0 -> system_u:object_r:shell_exec_t:s0 | ||
| + | /sbin/agetty system_u:object_r:getty_exec_t:s0 | ||
| + | /sbin/init system_u:object_r:bin_t:s0 -> system_u:object_r:init_exec_t:s0 | ||
| + | /usr/sbin/sshd system_u:object_r:sshd_exec_t:s0 | ||
| + | [root@vm-02 ~]# | ||
| + | </syntaxhighlight> | ||
| + | |||
| + | Для получения информации о контексте, в утилитах <code>ps</code>, <code>ls</code> имеется ключ <code>-Z</code>: | ||
| + | <syntaxhighlight lang="bash"> | ||
| + | [root@vm-02 ~]# ps --pid 1287 auwwZ | ||
| + | LABEL USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND | ||
| + | system_u:system_r:postfix_master_t:s0 root 1287 0.0 0.2 91700 2108 ? Ss 2017 0:07 /usr/libexec/postfix/master -w | ||
| + | system_u:system_r:getty_t:s0-s0:c0.c1023 root 2239 0.0 0.0 110004 796 tty1 Ss+ 2017 0:00 /sbin/agetty --noclear tty1 | ||
| + | unconfined_u:unconfined_r:unconfined_t:s0-s0:c0.c1023 root 18697 0.0 0.3 116524 3248 pts/0 Ss 13:06 0:00 -bash | ||
| + | unconfined_u:unconfined_r:unconfined_t:s0-s0:c0.c1023 root 19190 0.0 0.1 130184 1440 pts/0 R+ 17:19 0:00 ps --pid 1287 auwwZ | ||
| + | [root@vm-02 ~]# ls -lahiZ /srv/repo/ | ||
| + | Packages/ repodata/ | ||
| + | [root@vm-02 ~]# ls -lahiZ /srv/repo/ | ||
| + | drwxr-xr-x. root root unconfined_u:object_r:var_t:s0 . | ||
| + | drwxr-xr-x. root root system_u:object_r:var_t:s0 .. | ||
| + | drwxr-xr-x. root root unconfined_u:object_r:var_t:s0 Packages | ||
| + | dr-xr-xr-x. root root system_u:object_r:iso9660_t:s0 repodata | ||
| + | [root@vm-02 ~]# | ||
| + | </syntaxhighlight> | ||
| + | Каждый контекст состоит из 3 меток: | ||
| + | {| class="wikitable" | ||
| + | |- | ||
| + | ! Название !! Описание | ||
| + | |- | ||
| + | | User || Может быть узнаваем по суффиксу <code>_u</code>. Никакого отношения к учетным записям пользователей не имеет. Настройка для сдачи RHCSA/RHCE не нужна. | ||
| + | |- | ||
| + | | Role || Может быть узнаваема по суффиксу <code>_r</code>. В более тонком управлении политиками <code>SELinux</code> конкретным пользвателям <code>SELinux</code>, могут быть присвоены конкретные роли <code>SELinux</code>. Настройка для сдачи RHCSA/RHCE не нужна. | ||
| + | |- | ||
| + | | Type || Может быть узнаваем по суффиксу <code>_t</code>. Разные типы контекстов применяются к разным демонам и файлам в операционной системе. Манипуляция данным типом меток требуется для сдачи экзаменов RHCSA/RHCE | ||
| + | |} | ||
| + | Для изменения типов контекстов следует использовать '''только''' утилиту <code>semanage</code>. Изменения, произведенные утилитой <code>chcon</code>, которая иногда встречается в документации, не переживают перемаркировку (relabeling) файловой системы, после которой происходит восстановление оригинального контекста из политики. | ||
| + | Для получения <code>man</code> страниц с описаниями типов контекстов следует запустить следующую команду: | ||
| + | <syntaxhighlight lang="bash"> | ||
| + | [root@vm-02 ~]# sepolicy manpage -ap /usr/share/man/man8 | ||
| + | /usr/share/man/man8/NetworkManager_selinux.8 | ||
| + | /usr/share/man/man8/abrt_selinux.8 | ||
| + | /usr/share/man/man8/abrt_dump_oops_selinux.8 | ||
| + | /usr/share/man/man8/abrt_handle_event_selinux.8 | ||
| + | .... | ||
| + | [root@vm-02 ~]# mandb | ||
| + | Purging old database entries in /usr/share/man... | ||
| + | Processing manual pages under /usr/share/man... | ||
| + | Updating index cache for path `/usr/share/man/man8'. Wait...mandb: warning: /usr/share/man/man8/afs_selinux.8*: competing extensions | ||
| + | mandb: warning: /usr/share/man/man8/apm_selinux.8*: competing extensions | ||
| + | mandb: warning: /usr/share/man/man8/ccs_selinux.8*: competing extensions | ||
| + | .... | ||
| + | 4 man subdirectories contained newer manual pages. | ||
| + | 865 manual pages were added. | ||
| + | 0 stray cats were added. | ||
| + | 0 old database entries were purged. | ||
| + | [root@vm-02 ~]# man -k _selinux | grep samba | ||
| + | samba_net_selinux (8) - Security Enhanced Linux Policy for the samba_net processes | ||
| + | samba_selinux (8) - Security Enhanced Linux Policy for the smbd processes | ||
| + | samba_unconfined_net_selinux (8) - Security Enhanced Linux Policy for the samba_unconfined_net processes | ||
| + | samba_unconfined_script_selinux (8) - Security Enhanced Linux Policy for the samba_unconfined_script processes | ||
| + | sambagui_selinux (8) - Security Enhanced Linux Policy for the sambagui processes | ||
| + | [root@vm-02 ~]# | ||
| + | </syntaxhighlight> | ||
| + | Сразу откроем порты в файрволе: | ||
| + | <syntaxhighlight lang="bash"> | ||
| + | [root@vm-01 ~]# firewall-cmd --add-service=http --permanent | ||
| + | success | ||
| + | [root@vm-01 ~]# firewall-cmd --reload | ||
| + | success | ||
| + | [root@vm-01 ~]# firewall-cmd --list-all | ||
| + | public (active) | ||
| + | target: default | ||
| + | icmp-block-inversion: no | ||
| + | interfaces: eth0 eth1 | ||
| + | sources: | ||
| + | services: dhcpv6-client dns http ssh | ||
| + | ports: 3260/tcp | ||
| + | protocols: | ||
| + | masquerade: yes | ||
| + | forward-ports: | ||
| + | sourceports: | ||
| + | icmp-blocks: | ||
| + | rich rules: | ||
| + | |||
| + | [root@vm-01 ~]# | ||
| + | </syntaxhighlight> | ||
| + | |||
| + | == Применение SELinux на примере Apache == | ||
| + | ==== Установка и настройка вебсервера ==== | ||
| + | Устанавливаем вебсервер: | ||
| + | <syntaxhighlight lang="bash"> | ||
| + | [root@vm-01 ~]# yum install -y httpd | ||
| + | </syntaxhighlight> | ||
| + | Создадим тестовый виртуальный хост: | ||
| + | <syntaxhighlight lang="bash"> | ||
| + | [root@vm-01 ~]# cp /usr/share/doc/httpd-2.4.6/httpd-vhosts.conf /etc/httpd/conf.d/test.conf | ||
| + | </syntaxhighlight> | ||
| + | И приведем его к следующему виду: | ||
| + | <syntaxhighlight lang="bash"> | ||
| + | # Virtual Hosts | ||
| + | # | ||
| + | # Required modules: mod_log_config | ||
| + | |||
| + | # If you want to maintain multiple domains/hostnames on your | ||
| + | # machine you can setup VirtualHost containers for them. Most configurations | ||
| + | # use only name-based virtual hosts so the server doesn't need to worry about | ||
| + | # IP addresses. This is indicated by the asterisks in the directives below. | ||
| + | # | ||
| + | # Please see the documentation at | ||
| + | # <URL:http://httpd.apache.org/docs/2.4/vhosts/> | ||
| + | # for further details before you try to setup virtual hosts. | ||
| + | # | ||
| + | # You may use the command line option '-S' to verify your virtual host | ||
| + | # configuration. | ||
| + | |||
| + | # | ||
| + | # VirtualHost example: | ||
| + | # Almost any Apache directive may go into a VirtualHost container. | ||
| + | # The first VirtualHost section is used for all requests that do not | ||
| + | # match a ServerName or ServerAlias in any <VirtualHost> block. | ||
| + | # | ||
| + | <VirtualHost *:80> | ||
| + | ServerAdmin webmaster@test.example.com | ||
| + | DocumentRoot "/home/andy/content" | ||
| + | ServerName test.example.com | ||
| + | ServerAlias www.test.example.com | ||
| + | ErrorLog "/var/log/httpd/test.example.com-error_log" | ||
| + | CustomLog "/var/log/httpd/test.example.com-access_log" common | ||
| + | Options Indexes FollowSymLinks | ||
| + | <Directory "/home/andy/content"> | ||
| + | Options Indexes FollowSymLinks | ||
| + | AllowOverride None | ||
| + | # Allow open access: | ||
| + | Require all granted | ||
| + | </Directory> | ||
| + | </VirtualHost> | ||
| + | </syntaxhighlight> | ||
| + | Переключимся в пользователя <code>andy</code>и создадим директорию <code>/home/andy/content</code> и в нем файл <code>index.html</code> следующего содержания: | ||
| + | <syntaxhighlight lang="bash"> | ||
| + | [andy@vm-01 ~]$ mkdir /home/andy/content | ||
| + | [andy@vm-01 ~]$ echo "This is the test configuration file! New!" >> /home/andy/content/index.html | ||
| + | [andy@vm-01 ~]$ cat /home/andy/content/index.html | ||
| + | This is the test configuration file | ||
| + | [andy@vm-01 ~]$ | ||
| + | </syntaxhighlight> | ||
| + | |||
| + | ==== Манипуляции с контекстом SELinux ==== | ||
| + | Теперь, переключившись обратно в пользователя <code>root</code>, необходимо присвоить правильный контекст директории, дабы наша страница отображалась корректно. Следующая последовательность действий описана в <code>man 8 semanage-fcontext</code>. Поскольку наш контент не подразумевает каких-то выполняемых файлов, либо файлов изменяемых пользователем, то вводим следующие команды: | ||
| + | <syntaxhighlight lang="bash"> | ||
| + | [root@vm-01 andy]# semanage fcontext -at httpd_sys_content_t "/home/andy/content(/.*)?" | ||
| + | [root@vm-01 andy]# restorecon -vR /home/andy/content | ||
| + | restorecon reset /home/andy/content context unconfined_u:object_r:user_home_t:s0->unconfined_u:object_r:httpd_sys_content_t:s0 | ||
| + | [root@vm-01 andy]# ls -lahiZ /home/andy/ | ||
| + | drwx------. andy andy unconfined_u:object_r:user_home_dir_t:s0 . | ||
| + | drwxr-xr-x. root root system_u:object_r:home_root_t:s0 .. | ||
| + | -rw-------. andy andy unconfined_u:object_r:user_home_t:s0 .bash_history | ||
| + | -rw-r--r--. andy andy unconfined_u:object_r:user_home_t:s0 .bash_logout | ||
| + | -rw-r--r--. andy andy unconfined_u:object_r:user_home_t:s0 .bash_profile | ||
| + | -rw-r--r--. andy andy unconfined_u:object_r:user_home_t:s0 .bashrc | ||
| + | drwxrwxr-x. andy andy unconfined_u:object_r:httpd_sys_content_t:s0 content | ||
| + | [root@vm-01 andy]# | ||
| + | </syntaxhighlight> | ||
| + | Полный список типов конткекста, можно получить введя команду <code>semanage fcontext -l</code>: | ||
| + | <syntaxhighlight lang="bash"> | ||
| + | [root@vm-01 ~]# semanage fcontext -l | grep "/var/www" | head | ||
| + | /var/www(/.*)? all files system_u:object_r:httpd_sys_content_t:s0 | ||
| + | /var/www(/.*)?/logs(/.*)? all files system_u:object_r:httpd_log_t:s0 | ||
| + | /var/www/[^/]*/cgi-bin(/.*)? all files system_u:object_r:httpd_sys_script_exec_t:s0 | ||
| + | /var/www/svn(/.*)? all files system_u:object_r:httpd_sys_rw_content_t:s0 | ||
| + | /var/www/git(/.*)? all files system_u:object_r:git_content_t:s0 | ||
| + | /var/www/perl(/.*)? all files system_u:object_r:httpd_sys_script_exec_t:s0 | ||
| + | /var/www/wiki[0-9]?\.php regular file system_u:object_r:mediawiki_content_t:s0 | ||
| + | /var/www/wiki[0-9]?(/.*)? all files system_u:object_r:mediawiki_rw_content_t:s0 | ||
| + | /var/www/html(/.*)?/uploads(/.*)? all files system_u:object_r:httpd_sys_rw_content_t:s0 | ||
| + | /var/www/html(/.*)?/wp-content(/.*)? all files system_u:object_r:httpd_sys_rw_content_t:s0 | ||
| + | [root@vm-01 ~]# | ||
| + | </syntaxhighlight> | ||
| + | После внесения изменений в конфигурационный файл, проверяем синтаксис и запускаем <code>Apache</code>: | ||
| + | <syntaxhighlight lang="bash"> | ||
| + | [root@vm-01 ~]# httpd -t -D DUMP_VHOSTS | ||
| + | AH00558: httpd: Could not reliably determine the server's fully qualified domain name, using 192.168.122.158. Set the 'ServerName' directive globally to suppress this message | ||
| + | VirtualHost configuration: | ||
| + | *:80 test.example.com (/etc/httpd/conf.d/test.conf:23) | ||
| + | [root@vm-01 ~]# systemctl start httpd | ||
| + | [root@vm-01 ~]# systemctl is-active httpd | ||
| + | active | ||
| + | [root@vm-01 ~]# | ||
| + | </syntaxhighlight> | ||
| + | Однако, если сразу попытаться получить страницу - то работать не будет так как вебсерверу не разрешено читать файлы в домашних директориях пользователя. Для изменения этого поведения, необходимо в файле | ||
| + | <code>/etc/httpd/conf.d/userdir.conf</code> выставить переменную <code>UserDir content</code>, а директории пользователя <code>andy</code>, надо изменить права: | ||
| + | <syntaxhighlight lang="bash"> | ||
| + | [root@vm-01 ~]# chmod 711 /home/andy/ | ||
| + | [root@vm-01 ~]# ls -lahiZ /home/ | ||
| + | drwxr-xr-x. root root system_u:object_r:home_root_t:s0 . | ||
| + | dr-xr-xr-x. root root system_u:object_r:root_t:s0 .. | ||
| + | drwx--x--x. andy andy unconfined_u:object_r:user_home_dir_t:s0 andy | ||
| + | [root@vm-01 ~]# | ||
| + | </syntaxhighlight> | ||
| + | Теперь остался один нюанс, включение булевых настроек <code>SELinux</code>, регулирующих некоторые аспекты поведения демонов. Надо разрешить чтение домашних директорий вебсервером <code>Apache</code>, в контексте <code>SELinux</code> (работать не должно, но в реальности правило SELinux сломано, поэтому работать будет без выполнения действий, описанных ниже): | ||
| + | <syntaxhighlight lang="bash"> | ||
| + | [root@vm-01 ~]# getsebool -a | grep httpd_ | grep home | ||
| + | httpd_enable_homedirs --> off | ||
| + | [root@vm-01 ~]# setsebool -P httpd_enable_homedirs on | ||
| + | [root@vm-01 ~]# getsebool -a | grep httpd_ | grep home | ||
| + | httpd_enable_homedirs --> on | ||
| + | [root@vm-01 ~]# | ||
| + | </syntaxhighlight> | ||
| + | |||
| + | ==== Проверка ==== | ||
| + | С виртуальной машины <code>vm-02</code> обратимся к странице при помощи утилиты <code>curl</code>: | ||
| + | <syntaxhighlight lang="bash"> | ||
| + | [root@vm-02 ~]# curl "http://192.168.1.1/~andy/index.html" | ||
| + | This is the test configuration file! | ||
| + | [root@vm-02 ~]# | ||
| + | </syntaxhighlight> | ||
| + | |||
| + | == Ссылки == | ||
| + | [https://access.redhat.com/documentation/en-us/red_hat_enterprise_linux/7/html/selinux_users_and_administrators_guide/index SELinux User's and Administrator's Guide]<br /> | ||
Текущая версия на 14:05, 22 января 2018
Содержание
Конфигурирование SELinux для поддержки сервиса
Предварительные требования
- Виртуальная машина с двумя сетевыми интерфейсами
- Установленные пакеты:
bash-completion,policycoreutils,policycoreutils-python,policycoreutils-devel,setroubleshoot-server
Общая информация
SELinux представляет собой систему принудительного контроля доступа и позволяет разделить
пользовательские данные от сервисов которые были скомпрометированы. SELinux позволяет
определить какой процесс, к каким сущностям (файлы, директории, порты, процессы, пользователи) может иметь доступ. Уровень доступа к сущностям
носит название контекст. Терминология SELinux:
| Название элемента | Описание |
|---|---|
| Policy | Набор правил, определяющих какой источник может иметь доступ к какой цели |
| Source domain | Объект, пытающийся получить доступ к цели. Обычно пользователь или процесс |
| Target domain | Сущность, к которой пытается получить доступ источник. Обычно файл или порт |
| Context | Метка безопасности, использующаяся для классификации объектов в SELinux |
| Rule | Конкретная часть политики, которая определяет какой источник имеет какие правила доступа к какой цели. |
| Lables | Тоже самое, что и контекст, определяет какой источник имеет какие правила доступа к какой цели. |
В системе SELinux может находится в 3 состояниях:
enforcing - Политики SELinux включены и применяются.
permissive - Политики SELinux включены, однако, вместо их применения, печатаются предупреждения. Данное поведение рекомендовано для отладки и поиска ошибок в файле /var/log/audit/audit.log
disabled - Политики SELinux не применяются. Не рекомендовано к использованию, ибо ведет к несдаче экзамена.
Данные настройки можно внести в конфигурационный файл /etc/sysconfig/selinux:
# 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=enforcing
# SELINUXTYPE= can take one of these two values:
# targeted - Targeted processes are protected,
# minimum - Modification of targeted policy. Only selected processes are protected.
# mls - Multi Level Security protection.
SELINUXTYPE=targetedПри условии работоспособности SELinux, в командной строке его можно переключать между режимами enforcing и permissive при помощи команд getenforce/setenforce. Например:
[root@vm-02 ~]# getenforce
Enforcing
[root@vm-02 ~]# setenforce 0
[root@vm-02 ~]# getenforce
Permissive
[root@vm-02 ~]# setenforce 1
[root@vm-02 ~]# getenforce
Enforcing
[root@vm-02 ~]#Так же, информацию о работоспособности SELinux и загруженных политиках, можно получить при помощи команды sestatus:
[root@vm-02 ~]# sestatus -v
SELinux status: enabled
SELinuxfs mount: /sys/fs/selinux
SELinux root directory: /etc/selinux
Loaded policy name: targeted
Current mode: enforcing
Mode from config file: enforcing
Policy MLS status: enabled
Policy deny_unknown status: allowed
Max kernel policy version: 28
Process contexts:
Current context: unconfined_u:unconfined_r:unconfined_t:s0-s0:c0.c1023
Init context: system_u:system_r:init_t:s0
/usr/sbin/sshd system_u:system_r:sshd_t:s0-s0:c0.c1023
File contexts:
Controlling terminal: unconfined_u:object_r:user_devpts_t:s0
/etc/passwd system_u:object_r:passwd_file_t:s0
/etc/shadow system_u:object_r:shadow_t:s0
/bin/bash system_u:object_r:shell_exec_t:s0
/bin/login system_u:object_r:login_exec_t:s0
/bin/sh system_u:object_r:bin_t:s0 -> system_u:object_r:shell_exec_t:s0
/sbin/agetty system_u:object_r:getty_exec_t:s0
/sbin/init system_u:object_r:bin_t:s0 -> system_u:object_r:init_exec_t:s0
/usr/sbin/sshd system_u:object_r:sshd_exec_t:s0
[root@vm-02 ~]#Для получения информации о контексте, в утилитах ps, ls имеется ключ -Z:
[root@vm-02 ~]# ps --pid 1287 auwwZ
LABEL USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND
system_u:system_r:postfix_master_t:s0 root 1287 0.0 0.2 91700 2108 ? Ss 2017 0:07 /usr/libexec/postfix/master -w
system_u:system_r:getty_t:s0-s0:c0.c1023 root 2239 0.0 0.0 110004 796 tty1 Ss+ 2017 0:00 /sbin/agetty --noclear tty1
unconfined_u:unconfined_r:unconfined_t:s0-s0:c0.c1023 root 18697 0.0 0.3 116524 3248 pts/0 Ss 13:06 0:00 -bash
unconfined_u:unconfined_r:unconfined_t:s0-s0:c0.c1023 root 19190 0.0 0.1 130184 1440 pts/0 R+ 17:19 0:00 ps --pid 1287 auwwZ
[root@vm-02 ~]# ls -lahiZ /srv/repo/
Packages/ repodata/
[root@vm-02 ~]# ls -lahiZ /srv/repo/
drwxr-xr-x. root root unconfined_u:object_r:var_t:s0 .
drwxr-xr-x. root root system_u:object_r:var_t:s0 ..
drwxr-xr-x. root root unconfined_u:object_r:var_t:s0 Packages
dr-xr-xr-x. root root system_u:object_r:iso9660_t:s0 repodata
[root@vm-02 ~]#Каждый контекст состоит из 3 меток:
| Название | Описание |
|---|---|
| User | Может быть узнаваем по суффиксу _u. Никакого отношения к учетным записям пользователей не имеет. Настройка для сдачи RHCSA/RHCE не нужна.
|
| Role | Может быть узнаваема по суффиксу _r. В более тонком управлении политиками SELinux конкретным пользвателям SELinux, могут быть присвоены конкретные роли SELinux. Настройка для сдачи RHCSA/RHCE не нужна.
|
| Type | Может быть узнаваем по суффиксу _t. Разные типы контекстов применяются к разным демонам и файлам в операционной системе. Манипуляция данным типом меток требуется для сдачи экзаменов RHCSA/RHCE
|
Для изменения типов контекстов следует использовать только утилиту semanage. Изменения, произведенные утилитой chcon, которая иногда встречается в документации, не переживают перемаркировку (relabeling) файловой системы, после которой происходит восстановление оригинального контекста из политики.
Для получения man страниц с описаниями типов контекстов следует запустить следующую команду:
[root@vm-02 ~]# sepolicy manpage -ap /usr/share/man/man8
/usr/share/man/man8/NetworkManager_selinux.8
/usr/share/man/man8/abrt_selinux.8
/usr/share/man/man8/abrt_dump_oops_selinux.8
/usr/share/man/man8/abrt_handle_event_selinux.8
....
[root@vm-02 ~]# mandb
Purging old database entries in /usr/share/man...
Processing manual pages under /usr/share/man...
Updating index cache for path `/usr/share/man/man8'. Wait...mandb: warning: /usr/share/man/man8/afs_selinux.8*: competing extensions
mandb: warning: /usr/share/man/man8/apm_selinux.8*: competing extensions
mandb: warning: /usr/share/man/man8/ccs_selinux.8*: competing extensions
....
4 man subdirectories contained newer manual pages.
865 manual pages were added.
0 stray cats were added.
0 old database entries were purged.
[root@vm-02 ~]# man -k _selinux | grep samba
samba_net_selinux (8) - Security Enhanced Linux Policy for the samba_net processes
samba_selinux (8) - Security Enhanced Linux Policy for the smbd processes
samba_unconfined_net_selinux (8) - Security Enhanced Linux Policy for the samba_unconfined_net processes
samba_unconfined_script_selinux (8) - Security Enhanced Linux Policy for the samba_unconfined_script processes
sambagui_selinux (8) - Security Enhanced Linux Policy for the sambagui processes
[root@vm-02 ~]#Сразу откроем порты в файрволе:
[root@vm-01 ~]# firewall-cmd --add-service=http --permanent
success
[root@vm-01 ~]# firewall-cmd --reload
success
[root@vm-01 ~]# firewall-cmd --list-all
public (active)
target: default
icmp-block-inversion: no
interfaces: eth0 eth1
sources:
services: dhcpv6-client dns http ssh
ports: 3260/tcp
protocols:
masquerade: yes
forward-ports:
sourceports:
icmp-blocks:
rich rules:
[root@vm-01 ~]#Применение SELinux на примере Apache
Установка и настройка вебсервера
Устанавливаем вебсервер:
[root@vm-01 ~]# yum install -y httpdСоздадим тестовый виртуальный хост:
[root@vm-01 ~]# cp /usr/share/doc/httpd-2.4.6/httpd-vhosts.conf /etc/httpd/conf.d/test.confИ приведем его к следующему виду:
# Virtual Hosts
#
# Required modules: mod_log_config
# If you want to maintain multiple domains/hostnames on your
# machine you can setup VirtualHost containers for them. Most configurations
# use only name-based virtual hosts so the server doesn't need to worry about
# IP addresses. This is indicated by the asterisks in the directives below.
#
# Please see the documentation at
# <URL:http://httpd.apache.org/docs/2.4/vhosts/>
# for further details before you try to setup virtual hosts.
#
# You may use the command line option '-S' to verify your virtual host
# configuration.
#
# VirtualHost example:
# Almost any Apache directive may go into a VirtualHost container.
# The first VirtualHost section is used for all requests that do not
# match a ServerName or ServerAlias in any <VirtualHost> block.
#
<VirtualHost *:80>
ServerAdmin webmaster@test.example.com
DocumentRoot "/home/andy/content"
ServerName test.example.com
ServerAlias www.test.example.com
ErrorLog "/var/log/httpd/test.example.com-error_log"
CustomLog "/var/log/httpd/test.example.com-access_log" common
Options Indexes FollowSymLinks
<Directory "/home/andy/content">
Options Indexes FollowSymLinks
AllowOverride None
# Allow open access:
Require all granted
</Directory>
</VirtualHost>Переключимся в пользователя andyи создадим директорию /home/andy/content и в нем файл index.html следующего содержания:
[andy@vm-01 ~]$ mkdir /home/andy/content
[andy@vm-01 ~]$ echo "This is the test configuration file! New!" >> /home/andy/content/index.html
[andy@vm-01 ~]$ cat /home/andy/content/index.html
This is the test configuration file
[andy@vm-01 ~]$Манипуляции с контекстом SELinux
Теперь, переключившись обратно в пользователя root, необходимо присвоить правильный контекст директории, дабы наша страница отображалась корректно. Следующая последовательность действий описана в man 8 semanage-fcontext. Поскольку наш контент не подразумевает каких-то выполняемых файлов, либо файлов изменяемых пользователем, то вводим следующие команды:
[root@vm-01 andy]# semanage fcontext -at httpd_sys_content_t "/home/andy/content(/.*)?"
[root@vm-01 andy]# restorecon -vR /home/andy/content
restorecon reset /home/andy/content context unconfined_u:object_r:user_home_t:s0->unconfined_u:object_r:httpd_sys_content_t:s0
[root@vm-01 andy]# ls -lahiZ /home/andy/
drwx------. andy andy unconfined_u:object_r:user_home_dir_t:s0 .
drwxr-xr-x. root root system_u:object_r:home_root_t:s0 ..
-rw-------. andy andy unconfined_u:object_r:user_home_t:s0 .bash_history
-rw-r--r--. andy andy unconfined_u:object_r:user_home_t:s0 .bash_logout
-rw-r--r--. andy andy unconfined_u:object_r:user_home_t:s0 .bash_profile
-rw-r--r--. andy andy unconfined_u:object_r:user_home_t:s0 .bashrc
drwxrwxr-x. andy andy unconfined_u:object_r:httpd_sys_content_t:s0 content
[root@vm-01 andy]#Полный список типов конткекста, можно получить введя команду semanage fcontext -l:
[root@vm-01 ~]# semanage fcontext -l | grep "/var/www" | head
/var/www(/.*)? all files system_u:object_r:httpd_sys_content_t:s0
/var/www(/.*)?/logs(/.*)? all files system_u:object_r:httpd_log_t:s0
/var/www/[^/]*/cgi-bin(/.*)? all files system_u:object_r:httpd_sys_script_exec_t:s0
/var/www/svn(/.*)? all files system_u:object_r:httpd_sys_rw_content_t:s0
/var/www/git(/.*)? all files system_u:object_r:git_content_t:s0
/var/www/perl(/.*)? all files system_u:object_r:httpd_sys_script_exec_t:s0
/var/www/wiki[0-9]?\.php regular file system_u:object_r:mediawiki_content_t:s0
/var/www/wiki[0-9]?(/.*)? all files system_u:object_r:mediawiki_rw_content_t:s0
/var/www/html(/.*)?/uploads(/.*)? all files system_u:object_r:httpd_sys_rw_content_t:s0
/var/www/html(/.*)?/wp-content(/.*)? all files system_u:object_r:httpd_sys_rw_content_t:s0
[root@vm-01 ~]#После внесения изменений в конфигурационный файл, проверяем синтаксис и запускаем Apache:
[root@vm-01 ~]# httpd -t -D DUMP_VHOSTS
AH00558: httpd: Could not reliably determine the server's fully qualified domain name, using 192.168.122.158. Set the 'ServerName' directive globally to suppress this message
VirtualHost configuration:
*:80 test.example.com (/etc/httpd/conf.d/test.conf:23)
[root@vm-01 ~]# systemctl start httpd
[root@vm-01 ~]# systemctl is-active httpd
active
[root@vm-01 ~]#Однако, если сразу попытаться получить страницу - то работать не будет так как вебсерверу не разрешено читать файлы в домашних директориях пользователя. Для изменения этого поведения, необходимо в файле
/etc/httpd/conf.d/userdir.conf выставить переменную UserDir content, а директории пользователя andy, надо изменить права:
[root@vm-01 ~]# chmod 711 /home/andy/
[root@vm-01 ~]# ls -lahiZ /home/
drwxr-xr-x. root root system_u:object_r:home_root_t:s0 .
dr-xr-xr-x. root root system_u:object_r:root_t:s0 ..
drwx--x--x. andy andy unconfined_u:object_r:user_home_dir_t:s0 andy
[root@vm-01 ~]#Теперь остался один нюанс, включение булевых настроек SELinux, регулирующих некоторые аспекты поведения демонов. Надо разрешить чтение домашних директорий вебсервером Apache, в контексте SELinux (работать не должно, но в реальности правило SELinux сломано, поэтому работать будет без выполнения действий, описанных ниже):
[root@vm-01 ~]# getsebool -a | grep httpd_ | grep home
httpd_enable_homedirs --> off
[root@vm-01 ~]# setsebool -P httpd_enable_homedirs on
[root@vm-01 ~]# getsebool -a | grep httpd_ | grep home
httpd_enable_homedirs --> on
[root@vm-01 ~]#Проверка
С виртуальной машины vm-02 обратимся к странице при помощи утилиты curl:
[root@vm-02 ~]# curl "http://192.168.1.1/~andy/index.html"
This is the test configuration file!
[root@vm-02 ~]#