Cambiar Estados y Modos de SELinux

El Equipo Documental de Fedora, Peter Boy (pboy) Versión F36 and newer Last review: 2023-08-09

Cambios permanentes en estados y modos de SELinux

Como se explica en Introducción a SELinux, SELinux se puede habilitar o deshabilitar. Cuando está habilitado, SELinux tiene dos modos: forzado y permisivo.

Emplee las instrucciones getenforce o sestatus para marcar en cual modo SELinux está ejecutándose. La instrucción getenforce devuelve Enforcing, Permissive, o Disabled.

La instrucción sestatus devuelve el estado SELinux y la normativa SELinux que está siendo utilizada:

[~]$ sestatus
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
Memory protection checking:     actual (secure)
Max kernel policy version:      31

Cuando los sistemas ejecutan SELinux en modo permisivo, los usuarios y procesos pueden etiquetar incorrectamente varios objetos del sistema de archivos. Los objetos del sistema de archivos creados con SELinux deshabilitado no se etiquetan. Este comportamiento causa problemas al cambiar al modo de aplicación, ya que SELinux depende de que los objetos del sistema de archivos estén etiquetados correctamente.

Para evitar que los archivos etiquetados incorrectamente o sin etiquetar causen problemas, los sistemas de archivos se reetiquetan automáticamente al cambiar del estado deshabilitado al modo permisivo o de aplicación. En el modo permisivo, use el comando fixfiles -F onboot como root para crear el archivo /.autorelabel con la opción -F para asegurar que los archivos se reetiqueten en el siguiente reinicio.

Habilitando SELinux

Cuando está habilitado, SELinux puede correr en uno de estos dos modos: hacer cumplir o permisivo. Las siguientes secciones muestran como cambiar permanentemente entre estos modos.

Mientras habilita SELinux sobre sistemas que previamente lo tenían deshabilitado, para evitar problemas, como sistemas que sean incapaces de arrancar o fallos en procesos, siga este procedimiento.

Requisitos previos
  • Están instalados los paquetes selinux-policy-targeted, selinux-policy, libselinux-utils y grubby. Para comprobar que un paquete concreto está instalado:

    $ rpm -q package_name
Procedimiento
  1. If your system has SELinux disabled at the kernel level (this is the recommended way, see [_disabling_selinux]), change this first. Check if you have the selinux=0 option in your kernel command line:

    $ cat /proc/cmdline
    BOOT_IMAGE=... ... selinux=0
    1. Quite la opción selinux=0 de la configuración del gestor de arranque usando grubby:

      $ sudo grubby --update-kernel ALL --remove-args selinux
    2. The change applies after you restart the system in one of the following steps.

  2. Ensure the file system is relabeled on the next boot:

    $ sudo fixfiles onboot
  3. Enable SELinux in permissive mode. For more information, see [_changing_to_permissive_mode].

  4. Restart your system:

    $ reboot
  5. Check for SELinux denial messages.

    $ sudo ausearch -m AVC,USER_AVC,SELINUX_ERR,USER_SELINUX_ERR -ts recent
  6. If there are no denials, switch to enforcing mode. For more information, see [_changing_to_enforcing_mode].

To run custom applications with SELinux in enforcing mode, choose one of the following scenarios:

Cambiando a modo permisivo

Utilice el siguiente procedimiento para cambiar permanentemente el modo SELinux a permisivo. Cuando SELinux se ejecuta en modo permisivo, la política de SELinux no se aplica. El sistema permanece operativo y SELinux no deniega ninguna operación, sino que solo registra los mensajes AVC, que pueden utilizarse para la resolución de problemas, la depuración y la mejora de las normativas de SELinux. En este caso, cada AVC se registra solo una vez.

Requisitos previos
  • Los paquetes selinux-policy-targeted, libselinux-utils, y policycoreutils son instalados en su sistema.

  • Los parámetros de kernel selinux=0 o enforcing=0 no son utilizados.

Procedimiento
  1. Open the /etc/selinux/config file in a text editor of your choice, for example:

# vi /etc/selinux/config
  1. Configure the SELINUX=permissive option:

# 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= can take one of these two values:
#       targeted - Targeted processes are protected,
#       mls - Multi Level Security protection.
SELINUXTYPE=targeted
  1. Restart the system:

    # reboot

Cambiar a modo forzado

Utilice los siguiente procedimiento para cambiar a SELinux a modo reforzado. Cuando SELinux esté ejecutándose en modo reforzado, refuerza la normativa de SELinux y deniega acceso basado en reglas de normativa de SELinux. En Fedora, el modo reforzado está habilitado por defecto cuando el sistema fue inicialmente instalado con SELinux.

Requisitos previos
  • Los paquetes selinux-policy-targeted, libselinux-utils, y policycoreutils son instalados en su sistema.

  • Los parámetros de kernel selinux=0 o enforcing=0 no son utilizados.

Procedimiento
  1. Open the /etc/selinux/config file in a text editor of your choice, for example:

    # vi /etc/selinux/config
  2. Configure the SELINUX=enforcing option:

    # 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,
    #       mls - Multi Level Security protection.
    SELINUXTYPE=targeted
  3. Save the change, and restart the system:

    # reboot

    On the next boot, SELinux relabels all the files and directories within the system and adds SELinux context for files and directories that were created when SELinux was disabled.

Verification
  1. After the system restarts, confirm that the getenforce command returns Enforcing:

    $ getenforce
    Enforcing

After changing to enforcing mode, SELinux may deny some actions because of incorrect or missing SELinux policy rules. To view what actions SELinux denies, enter the following command as root:

# ausearch -m AVC,USER_AVC,SELINUX_ERR,USER_SELINUX_ERR -ts today

Alternatively, with the setroubleshoot-server package installed, enter:

# grep "SELinux is preventing" /var/log/messages

Standard users can use the GUI setroubleshoot to file bugs directly to Bugzilla.

If SELinux is active and the Audit daemon (auditd) is not running on your system, then search for certain SELinux messages in the output of the dmesg command:

# dmesg | grep -i -e type=1300 -e type=1400

If SELinux denies some actions, see the Troubleshooting problems related to SELinux chapter in the RHEL 8 Using SELinux document for information about troubleshooting.

Deshabilitar SELinux

Utilice el procedimiento siguiente para deshabilitar permanentemente SELinux.

When SELinux is disabled, SELinux policy is not loaded at all; it is not enforced and AVC messages are not logged. Therefore, all benefits of running SELinux listed in Benefits of SELinux are lost.

It is recommended to use permissive mode instead of permanently disabling SELinux. See [_changing_to_permissive_mode] for more information about permissive mode.

Deshabilitar SELinux usando la opción SELINUX=disabled en /etc/selinux/config lleva a un proceso en el cual el kernel arranca con SELinux habilitado y conmuta al modo deshabilitado más tarde en el proceso de arranque. Debido a que pueden ocurrir fallos de memoria y condiciones en la marcha que originen fallos en el kernel, es preferible deshabilitar SELinux añadiendo el parámetro selinux=0 en la línea de comandos del kernel como se describe en Cambiar los modos SELinux en el momento del arranque si su escenario requiere realmente deshabilitar completamente SELinux.

Requisitos previos
  • The grubby package is installed:

    $ rpm -q grubby
    grubby-version
Procedimiento
  1. Open the /etc/selinux/config file in a text editor of your choice, for example:

    # vi /etc/selinux/config
  2. Configure the SELINUX=disabled option:

    # 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=disabled
    # SELINUXTYPE= can take one of these two values:
    #       targeted - Targeted processes are protected,
    #       mls - Multi Level Security protection.
    SELINUXTYPE=targeted
  3. Save the change, and restart your system:

# reboot
Verification
  • After reboot, confirm that the getenforce command returns Disabled:

    $ getenforce
    Disabled

Cambiadno Modos SELinux en Tiempo de Arranque

Al arrancar, puede poner varios parámetros del kernel para cambiar la manera de ejecutar SELinux:

enforcing=0

Al configurar este parámetro, el sistema se inicia en modo permisivo, lo cual resulta útil para solucionar problemas. Usar el modo permisivo podría ser la única opción para detectar un problema si el sistema de archivos está demasiado corrupto. Además, en modo permisivo, el sistema continúa creando las etiquetas correctamente. Los mensajes AVC que se crean en este modo pueden ser diferentes a los del modo reforzado.

In permissive mode, only the first denial from a series of the same denials is reported. However, in enforcing mode, you might get a denial related to reading a directory, and an application stops. In permissive mode, you get the same AVC message, but the application continues reading files in the directory and you get an AVC for each denial in addition.

selinux=0

This parameter causes the kernel to not load any part of the SELinux infrastructure. The init scripts notice that the system booted with the selinux=0 parameter and touch the /.autorelabel file. This causes the system to automatically relabel the next time you boot with SELinux enabled.

Using the selinux=0 parameter is not recommended. To debug your system, prefer using permissive mode.

autorelabel=1

This parameter forces the system to relabel similarly to the following commands:

# touch /.autorelabel
# reboot

If a file system contains a large amount of mislabeled objects, start the system in permissive mode to make the autorelabel process successful.

For additional SELinux-related kernel boot parameters, such as checkreqprot, see the kernel-parameters.txt file. This file is available in the source package of your Linux kernel (.src.rpm). To download the source package containing the currently used kernel:

[~]# dnf download --source kernel