User:Ramix/Pruebas/SELinux

From ArchWiki

Category:Access control Category:Kernel Category:Red Hat

Esta traducción de SELinux fue revisada el 2020-02-28. Si existen cambios puede actualizarla o avisar al equipo de traducción.

SELinux (Security-Enhanced Linux) se compone de una serie de módulos del kernel de Linux denominados Módulos de Seguridad de Linux (LSM) que mejoran y extienden la seguridad de Linux. Uno de los aspectos relevantes de SELinux son las políticas de seguridad MAC. SELinux no es una distribución de Linux, es un conjunto de modificaciones que pueden aplicarse en sistemas operativos de tipo *NIX como Linux y BSD.

Existen tres requisitos para ejecutar SELinux en una distribución Linux: Tener activado SELinux en el kernel, tener instaladas las librerías y herramientas de SELinux, e instalar y configurar las políticas de SELinux en base a la Política de Referencia. Algunos programas necesitarán ser parcheados o recompilados para que funcionen con SELinux.

Estado actual en Arch Linux

Oficialmente SELinux no está soportado (consultar [1][2]). El estado del soporte no oficial es:

Nombre Estado Disponible en
Kernel con soporte de SELinux Implementado en linux, linux-zen y linux-hardened Disponible en los repositorios oficiales desde la versión 4.18.8.
Librerías y herramientas de SELinux Implementadas en AUR: https://aur.archlinux.org/packages/?O=0&K=selinux Trabajo finalizado en https://github.com/archlinuxhardened/selinux
Directivas de SELinux Trabajo en curso mediante Reference Policy como desarrollo principal Desarrollo principal: https://github.com/SELinuxProject/refpolicy (desde la edición 20170805 las directivas contemplan systemd y el directorio /usr/bin)

Resumen de cambios en AUR en comparación con los paquetes oficiales:

Nombre Estado y comentarios
linux Necesita los siguientes kernel parameters (Español) en el arranque de inicio: selinux=1 security=selinux
linux-hardened Necesita los siguientes kernel parameters (Español) en el arranque de inicio: selinux=1 security=selinux
coreutils Necesita una recompilación con el parámetro --with-selinux para su vínculo con libselinux
cronie Necesita una recompilación con el parámetro --with-selinux
dbus Necesita una recompilación con los parámetros --enable-libaudit y --enable-selinux
findutils Necesita una recompilación con libselinux instalado para activar algunas opciones de SELinux
iproute2 Necesita una recompilación con el parámetro --with-selinux
logrotate Necesita una recompilación con el parámetro --with-selinux
openssh Necesita una recompilación con el parámetro --with-selinux
pam Necesita una recompilación con el parámetro --enable-selinux para Linux-PAM ; Necesita un parche para pam_unix2, para eliminar una función que trae las versiones más recientes de libselinux
pambase Cambiar configuración para agregar pam_selinux.so a /etc/pam.d/system-login
psmisc Necesita una recompilación con el parámetro --with-selinux
shadow Necesita una recompilación con el parámetro --with-selinux
sudo Necesita una recompilación con el parámetro --with-selinux
systemd Necesita una recompilación con los parámetros --enable-audit y --enable-selinux
util-linux Necesita una recompilación con el parámetro --with-selinux

El resto de paquetes relacionados con SELinux pueden incluirse sin riesgo alguno.

Conceptos: Control de Acceso Obligatorio

Nota: Esta sección está orientada para principiantes, en caso de saber qué hace y cómo funciona SELinux se puede ir directamente a la sección de instalación.

Antes de utilizar SELinux es necesario entender qué hace. Para decirlo de una forma simple, SELinux utiliza el Control de Acceso Obligatorio (MAC) en lugar del Control de Acceso Discrecional (DAC) que utiliza Linux tradicionalmente por defecto. El modelo de permisos DAC se basa en la gestión de permisos de lectura, escritura y ejecución (rwx) de usuarios y grupos sobre recursos como ficheros por parte del usuario que crea el fichero. El modelo de permisos MAC la gestiona un administrador de seguridad (no el usuario que crea un fichero) y establece una política de seguridad basada en reglas donde todos los usuarios están obligados a cumplirla.

Un ejemplo puede ser el uso del comando sudo. Con las políticas DAC, el usuario que utiliza sudo tiene los mismos privilegios que el usuario root de forma temporal, sin restricciones en todo el sistema. Con las políticas MAC, si el administrador de seguridad establece que un usuario solo tendrá acceso a un conjunto determinado de ficheros, da igual el sistema de escalación de privilegios que pueda utilizar este usuario (incluyendo sudo), pues el usuario seguirá sin poder acceder a los ficheros que se encuentren fuera del conjunto determinado por la política de seguridad MAC, a no ser que esta política de seguridad lo permita. Por tanto, si un usuario o proceso utiliza sudo en una máquina con SELinux e intenta acceder a ficheros más allá de la política de seguridad MAC que se le aplique, este acceso no será permitido y fallará.

Otro ejemplo es el uso de los permisos tradicionales sobre ficheros (-rwxr-xr-x). En el caso de utilizar DAC, el propietario de un fichero o cualquier otro usuario que tenga permiso suficiente sobre ese fichero puede cambiar sus permisos. Sin embargo con MAC, un administrador de seguridad puede bloquear los permisos de un fichero determinado de forma que ningún usuario pueda cambiarlos, hasta que exista una política que lo permita.

Como puede imaginarse, utilizar MAC es particularmente beneficioso cuando existen procesos de alto riesgo que pueden ser potencialmente comprometidos, como servidores web y similares. El uso de DAC implica que si un proceso es comprometido tiene más posibilidades de escalar privilegios y comprometer al sistema completo.

Hay más información en wikipedia:Mandatory access control.

Instalación de SELinux

Descripción de paquetes

Todos los paquetes relacionados con SELinux pertenecen al grupo selinux de AUR.

Paquetes compatibles con SELinux

coreutils-selinuxAUR
Paquete coreutils adaptado y compilado con soporte de SELinux. Sustituye al paquete coreutils.
cronie-selinuxAUR
Bifurcación de Fedora de Vixie cron con soporte de SeLinux. Sustituye al paquete cronie.
dbus-selinuxAUR
An SELinux aware version of D-Bus. It replaces the dbus package.
findutils-selinuxAUR
Patched findutils package compiled with SELinux support to make searching of files with specified security context possible. It replaces the findutils package.
iproute2-selinuxAUR
iproute2 package compiled with SELinux support; for example, it adds the -Z option to ss. It replaces the iproute2 package.
logrotate-selinuxAUR
Logrotate package compiled with SELinux support. It replaces the logrotate package.
openssh-selinuxAUR
OpenSSH package compiled with SELinux support to set security context for user sessions. It replaces the openssh package.
pam-selinuxAUR and pambase-selinuxAUR
PAM package with pam_selinux.so. and the underlying base package. They replace the pam and pambase packages respectively.
psmisc-selinuxAUR
Psmisc package compiled with SELinux support; for example, it adds the -Z option to killall. It replaces the psmisc package.
shadow-selinuxAUR
Shadow package compiled with SELinux support; contains a modified /etc/pam.d/login file to set correct security context for user after login. It replaces the shadow package.
sudo-selinuxAUR
Modified sudo package compiled with SELinux support which sets the security context correctly. It replaces the sudo package.
systemd-selinuxAUR
An SELinux aware version of Systemd. It replaces the systemd package.
util-linux-selinuxAUR
Modified util-linux package compiled with SELinux support enabled. It replaces the util-linux package.

SELinux userspace utilities

checkpolicyAUR
Tools to build SELinux policy
mcstransAUR
Daemon which is used by libselinux to translate MCS labels
libselinuxAUR
Library for security-aware applications. Python bindings needed for semanage and setools now included.
libsemanageAUR
Library for policy management. Python bindings needed for semanage and setools now included.
libsepolAUR
Library for binary policy manipulation.
policycoreutilsAUR
SELinux core utils such as newrole, setfiles, etc.
restorecondAUR
Daemon which maintains the label of some files
secilcAUR
Compiler for SELinux policies written in CIL (Common Intermediate Language)
selinux-dbus-configAUR
DBus service which allows managing SELinux configuration
selinux-guiAUR
SELinux GUI tools (system-config-selinux)
selinux-pythonAUR and selinux-python2AUR
SELinux python tools and libraries (semanage, sepolgen, sepolicy, etc.)
selinux-sandboxAUR
Sandboxing tool for SELinux
semodule-utilsAUR
Tools to handle SELinux modules when building a policy

SELinux policy packages

selinux-refpolicy-srcAUR
Reference policy sources
selinux-refpolicy-gitAUR
Reference policy git master (https://github.com/SELinuxProject/refpolicy) built with configuration specific for Arch Linux
selinux-refpolicy-archAUR
Precompiled modular Reference policy with headers and documentation but without sources. Development Arch Linux Refpolicy patches included, which fixes issues related to path labeling and systemd support. These patches are also sent to Reference Policy maintainers and their inclusion in selinux-refpolicy-archAUR is mainly a way to perform updates between Refpolicy releases.

Other SELinux tools

setoolsAUR
CLI and GUI tools to manage SELinux
selinux-alpm-hookAUR
pacman hook to label files accordingly to SELinux policy when installing and updating packages

Installation

There are two methods to install the requisite SELinux packages.

Via AUR

After all these steps, you can install a SELinux kernel (like linux-selinuxAUR) and a policy (like selinux-refpolicy-archAUR or selinux-refpolicy-gitAUR).

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):

 git clone https://github.com/archlinuxhardened/selinux
 cd selinux
 ./recv_gpg_keys.sh
 ./build_and_install_all.sh

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.

Changing boot loader configuration

If you have installed a new kernel, make sure that you update your bootloader accordingly to boot on it. Moreover you may need to add security=selinux selinux=1 to the kernel command line. More precisely, if the kernel configuration does not set CONFIG_DEFAULT_SECURITY_SELINUX, security=selinux is needed, and if it contains CONFIG_SECURITY_SELINUX_BOOTPARAM=y CONFIG_SECURITY_SELINUX_BOOTPARAM_VALUE=0, selinux=1 is needed.

GRUB

Add security=selinux selinux=1 to GRUB_CMDLINE_LINUX_DEFAULT variable in /etc/default/grub Run the following command:

# grub-mkconfig -o /boot/grub/grub.cfg

Syslinux

Change your syslinux.cfg file by adding:

/boot/syslinux/syslinux.cfg
LABEL arch-selinux
         LINUX ../vmlinuz-linux-selinux
         APPEND root=/dev/sda2 ro security=selinux selinux=1
         INITRD ../initramfs-linux-selinux.img

at the end. Change "linux-selinux" to whatever kernel you are using.

systemd-boot

Create a new loader entry, for example in /boot/loader/entries/arch-selinux.conf:

/boot/loader/entries/arch-selinux.conf
title Arch Linux SELinux
linux /vmlinuz-linux-selinux
initrd /initramfs-linux-selinux.img
options root=/dev/sda2 ro selinux=1 security=selinux

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:

# 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

Installing a policy

Warning: The reference policy as given by SELinuxProject is not very good for Arch Linux, as before release 20170805 almost no file were labelled correctly. The major problems were:
  • /lib and /usr/lib were considered different (and also /bin, /sbin, /usr/bin and /usr/sbin). This introduced some instability when applying labels to the whole system, as files in these folders might be seen with 2 (or 4) different labels.
  • systemd was not yet supported (C. PeBenito, main developer of the refpolicy, announced its willingness to work on it in its github repository in October 2014, http://oss.tresys.com/pipermail/refpolicy/2014-October/007430.html)
Since refpolicy release 20170805 these two points have been addressed, but most people submitting patches to improve the policy use an other distribution (Debian, Gentoo, RHEL, etc.). Therefore the compatibility with Arch Linux packages is not perfect (for example the policy may not support the most recent features of a program).

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-srcAUR 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:

# make bare
# make conf
# make install

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:

# make load

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):

/etc/selinux/config
# This file controls the state of SELinux on the system.
# SELINUX= can take one of these three values:
#       enforcing - SELinux security policy is enforced.
#                   Set this value once you know for sure that SELinux is configured the way you like it and that your system is ready for deployment
#       permissive - SELinux prints warnings instead of enforcing.
#                    Use this to customise your SELinux policies and booleans prior to deployment. Recommended during policy development.
#       disabled - No SELinux policy is loaded.
#                  This is not a recommended setting, for it may cause problems with file labelling
SELINUX=permissive
# SELINUXTYPE= takes the name of SELinux policy to
# be used. Current options are:
#       refpolicy (vanilla reference policy)
#       <custompolicy> - Substitute <custompolicy> with the name of any custom policy you choose to load
SELINUXTYPE=refpolicy

Now, you may reboot. After rebooting, run:

# restorecon -r /

to label your filesystem.

Now, make a file requiredmod.te with the contents:

requiredmod.te
module requiredmod 1.0;

require {
        type devpts_t;
        type kernel_t;
        type device_t;
        type var_run_t;
        type udev_t;
        type hugetlbfs_t;
        type udev_tbl_t;
        type tmpfs_t;
        class sock_file write;
        class unix_stream_socket { read write ioctl };
        class capability2 block_suspend;
        class dir { write add_name };
        class filesystem associate;
}

#============= devpts_t ==============
allow devpts_t device_t:filesystem associate;

#============= hugetlbfs_t ==============
allow hugetlbfs_t device_t:filesystem associate;

#============= kernel_t ==============
allow kernel_t self:capability2 block_suspend;

#============= tmpfs_t ==============
allow tmpfs_t device_t:filesystem associate;

#============= udev_t ==============
allow udev_t kernel_t:unix_stream_socket { read write ioctl };
allow udev_t udev_tbl_t:dir { write add_name };
allow udev_t var_run_t:sock_file write;

and run the following commands:

# checkmodule -m -o requiredmod.mod requiredmod.te
# semodule_package -o requiredmod.pp -m requiredmod.mod
# semodule -i requiredmod.pp

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:

 git clone https://github.com/archlinuxhardened/selinux
 cd selinux/_vagrant
 vagrant up
 vagrant ssh

Post-installation steps

You can check that SELinux is working with sestatus. You should get something like:

SELinux status:                 enabled
SELinuxfs mount:                /sys/fs/selinux
SELinux root directory:         /etc/selinux
Loaded policy name:             refpolicy
Current mode:                   permissive
Mode from config file:          permissive
Policy MLS status:              disabled
Policy deny_unknown status:     allowed
Max kernel policy version:      28

To maintain correct context, you can use restorecond:

# systemctl enable restorecond

To switch to enforcing mode without rebooting, you can use:

# echo 1 > /sys/fs/selinux/enforce

Swapfiles

If you have a swap file instead of a swap partition, issue the following commands in order to set the appropriate security context:

# semanage fcontext -a -t swapfile_t "/path/to/swapfile"
# restorecon /path/to/swapfile

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:

$ls -lZ /var/www/html/index.html
-rw-r--r--  username username system_u:object_r:httpd_sys_content_t /var/www/html/index.html

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:role:type[:level]

To explain:

  1. User: The SELinux user identity. This can be associated to one or more roles that the SELinux user is allowed to use.
  2. Role: The SELinux role. This can be associated to one or more types the SELinux user is allowed to access.
  3. 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.
  4. 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 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:

# journalctl _SELINUX_CONTEXT=system_u:system_r:policykit_t:s0

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

Reporting issues

Please report issues on GitHub: https://github.com/archlinuxhardened/selinux/issues

See also