Getting started with SELinux

This page has been converted from the Fedora Project Wiki and cleaned up for publishing here on the Fedora Docs Portal, but it has not yet been reviewed for technical accuracy. This means any information on this page may be outdated or inaccurate. Reviews for technical accuracy are greatly appreciated. If you want to help, see the README file in the source repository for instructions.

Introduction to SELinux

Security Enhanced Linux (SELinux) provides an additional layer of system security. SELinux fundamentally answers the question: May <subject> do <action> to <object>?, for example: May a web server access files in users' home directories?

The standard access policy based on the user, group, and other permissions, known as Discretionary Access Control (DAC), does not enable system administrators to create comprehensive and fine-grained security policies, such as restricting specific applications to only viewing log files, while allowing other applications to append new data to the log files.

SELinux implements Mandatory Access Control (MAC). Every process and system resource has a special security label called a SELinux context. A SELinux context, sometimes referred to as a SELinux label, is an identifier which abstracts away the system-level details and focuses on the security properties of the entity. Not only does this provide a consistent way of referencing objects in the SELinux policy, but it also removes any ambiguity that can be found in other identification methods; for example, a file can have multiple valid path names on a system that makes use of bind mounts.

The SELinux policy uses these contexts in a series of rules which define how processes can interact with each other and the various system resources. By default, the policy does not allow any interaction unless a rule explicitly grants access.

It is important to remember that SELinux policy rules are checked after DAC rules. SELinux policy rules are not used if DAC rules deny access first, which means that no SELinux denial is logged if the traditional DAC rules prevent the access.

SELinux contexts have several fields: user, role, type, and security level. The SELinux type information is perhaps the most important when it comes to the SELinux policy, as the most common policy rule which defines the allowed interactions between processes and system resources uses SELinux types and not the full SELinux context. SELinux types usually end with _t. For example, the type name for the web server is httpd_t. The type context for files and directories normally found in /var/www/html/ is httpd_sys_content_t. The type contexts for files and directories normally found in /tmp and /var/tmp/ is tmp_t. The type context for web server ports is http_port_t.

For example, there is a policy rule that permits Apache (the web server process running as httpd_t) to access files and directories with a context normally found in /var/www/html/ and other web server directories (httpd_sys_content_t). There is no allow rule in the policy for files normally found in /tmp and /var/tmp/, so access is not permitted. With SELinux, even if Apache is compromised, and a malicious script gains access, it is still not able to access the /tmp directory.

SELinux_Apache_MariaDB_example
Figure 1. SELinux allows the Apache process running as httpd_t to access the /var/www/html/ directory and it denies the same process to access the /data/mysql/ directory because there is no allow rule for the httpd_t and mysqld_db_t type contexts). On the other hand, the MariaDB process running as mysqld_t is able to access the /data/mysql/ directory and SELinux also correctly denies the process with the mysqld_t type to access the /var/www/html/ directory labeled as httpd_sys_content_t.

Recursos Adicionales

To better understand SELinux basic concepts, see the following documentation:

Beneficios de ejecutar SELinux

SELinux proporciona los siguientes beneficios:

  • Todos los procesos y archivos están etiquetados. Las reglas de política SELinux definen como interactúan los procesos con los archivos, así como interactúan los procesos entre sí. Sólo está permitido el acceso si existe una regla de política SELinux que lo permite específicamente.

  • Control de acceso granular. Yendo más allá de los permisos UNIX tradicionales que se controlan a discreción del usuario y en base a las IDs de usuario y grupo de Linux, las decisiones de acceso de SELinux ase basan en toda la información disponible, tales como usuario SELinux, rol, tipo y , opcionalmente, un nivel de seguridad.

  • SELinux policy is administratively-defined and enforced system-wide.

  • Improved mitigation for privilege escalation attacks. Processes run in domains, and are therefore separated from each other. SELinux policy rules define how processes access files and other processes. If a process is compromised, the attacker only has access to the normal functions of that process, and to files the process has been configured to have access to. For example, if the Apache HTTP Server is compromised, an attacker cannot use that process to read files in user home directories, unless a specific SELinux policy rule was added or configured to allow such access.

  • SELinux can be used to enforce data confidentiality and integrity, as well as protecting processes from untrusted inputs.

However, SELinux is not:

  • antivirus software,

  • replacement for passwords, firewalls, and other security systems,

  • all-in-one security solution.

SELinux is designed to enhance existing security solutions, not replace them. Even when running SELinux, it is important to continue to follow good security practices, such as keeping software up-to-date, using hard-to-guess passwords, or firewalls. :experimental:

Ejemplos SELinux examples

Los siguientes ejemplos demuestran como SELinux incrementa la seguridad:

  • La acción predeterminada es denegar. Si no existe una regla de política de SELinux para permitir el acceso, como para un proceso que abre un archivo, se deniega el acceso.

  • SELinux puede confinar usuarios Linux. Existe un número de usuarios SELinux en la política SELinux. Los usuarios Linux pueden ser mapeados a usuarios confinados SELinux para tomar ventaja de las reglas de seguridad y de los mecanismos que se les aplican. Por ejemplo, mapeando un usuario Linux al usuario SELinux user_u, da como resultado un usuario Linux que no es capaz de ejecutar (a menos que se configure de otra manera) establecer ID de usuario (setuid) de aplicaciones, como sudo y su, además de evitar que ejecuten archivos y aplicaciones en su directorio home. Si se configura, esto evita que los usuarios ejecuten archivos maliciosos desde sus directorios home.

  • Mayor separación de procesos y datos. Los procesos corren en sus propios dominios, evitando que los procesos accedan a archivos usados por otros procesos, además de evitar que los procesos accedan a otros procesos. Por ejemplo, cuando está corriendo SELinux, a no ser que se configure de otra manera, un atacante no puede comprometer un servidor Samba y por lo tanto usar el servidor Samba como vector de ataque para leer y escribir archivos usados por otros procesos, como bases de datos MariaDB.

  • SELinux ayuda a mitigar los daños causados por errores de configuración. Los servidores de Sistema de Nombre de Dominio (DNS) replican con frecuencia información entre ellos en lo que se conoce como zona de transferencia. Los atacantes pueden usar la zona de transferencia para actualizar los servidores DNS con información falsa. Cuando está corriendo el Berkeley Internet Name Domain (BIND) como servidor DNS en Fedora, aún si un administrador olvidar limitar que servidores pueden llevar a cabo una zona de transferencia, la política SELinux predeterminada evita que los archivos de zona [1] sean actualizados usando la zona de transferencia, por el demonioBIND `named`mismo o por otros procesos.

  • Vea el artículo NetworkWorld.com, A seatbelt for server software: SELinux blocks real-world exploits[2], para información de respaldo sobre SELinux e información sobre diversas debilidades que SELinux ha evitado. :experimental:

SELinux architecture

SELinux is a Linux Security Module (LSM) that is built into the Linux kernel. The SELinux subsystem in the kernel is driven by a security policy which is controlled by the administrator and loaded at boot. All security-relevant, kernel-level access operations on the system are intercepted by SELinux and examined in the context of the loaded security policy. If the loaded policy allows the operation, it continues. Otherwise, the operation is blocked and the process receives an error.

SELinux decisions, such as allowing or disallowing access, are cached. This cache is known as the Access Vector Cache (AVC). When using these cached decisions, SELinux policy rules need to be checked less, which increases performance. Remember that SELinux policy rules have no effect if DAC rules deny access first. :experimental:

SELinux estados y modos

SELinux puede correr en una de estos tres modos: deshabilitado, permisivo o haciendo cumplir.

El modo deshabilitado está fuertemente desaconsejado; el sistema no sólo evita hacer cumplir la política SELinux, también evita etiquetar cualquier objeto persistente como archivos, haciendo difícil habilitar SELinux en el futuro.

En modo permisivo, el sistema actúa como si SELinux está haciendo cumpir la politica de seguridad cargada, incluyendo el etiquetado de objetos y emitiendo entradas de denegación de acceso en los registros, pero no hace ninguna operación de denegación. Mientras que no se recomienda para sistemas en producción, el modo permisivo puede ser útil para ayudar en el desarrollo de la política de SELinux.

El modo de hacer cumplir es el modo de operación predeterminado y recomendado; en el modo hacer cumplir SELinux trabaja normalmente, hacer cumplir carga la política de seguridad en todo el seguridad.

Use la utilidad setenforce para cambiar entre el modo hacer cumplir y el permisivo. Los cambios hechos con setenforce no persiste en los reinicios. Para cambiar a modo hacer cumplir, introduzca el comando setenforce 1`como usuario root de Linux. Para cambiar a modo permisivo, introduzca el comando [command]`setenforce 0. Use la utilidad getenforce para visualizar el modo actual de SELinux:

~]# getenforce
Enforcing
~]# setenforce 0
~]# getenforce
Permissive
~]# setenforce 1
~]# getenforce
Enforcing

En Fedora, usted puede establecer dominios individuales para modo permisivo mientras el sistema corre en modo hacer cumplir. Por ejemplo, para hacer el dominio httpd_t permisivo:

~]# semanage permissive -a httpd_t

1. Archivos de texto que incluyen información, como mapeos de nombre de host a dirección IP, que son usados por servidores DNS.
2. Marti, Don. "A seatbelt for server software: SELinux blocks real-world exploits". Publicado el 24 de Febrero de 2008. Visto el 27 de Agosto de 2009: https://www.networkworld.com/article/2283723/lan-wan/a-seatbelt-for-server-software--selinux-blocks-real-world-exploits.html.