linux selinux - ghdrako/doc_snipets GitHub Wiki

selinux

SELinux jest implementacją kilku modeli polityk bezpieczeństwa m.in.:

  • Mandatory Access Control (MAC) – model ochrony i zabezpieczania procesów, danych i urządzeń systemowych przed szkodliwym nadużyciem lub wykorzystaniem. MAC rozszerza model DAC, który jest aktualnie używany jako podstawowy model bezpieczeństwa w Linuksie
  • Flux Advanced Security Kernel (FLASK) – wsparcie dla MAC, czyli obsługa kontekstów bezpieczeństwa
  • Role-based access control (RBAC) – ograniczanie dostępu do zasobów systemowych na podstawie roli, jaką użytkownik pełni w systemie
  • Type Enforcement (TE) – przypisywanie atrybutów bezpieczeństwa (typów lub domen) obiektom systemowym.

SELinux does not change the Linux DAC implementation, nor can it override denials made by the Linux DAC permissions. If a regular system (without SELinux) prevents a particular access, there is nothing SELinux can do to override this decision. This is because the LSM hooks are triggered after the regular DAC permission checks execute, a conscious design decision from the LSM project.

SELinux makes a decision based on the context of both the subject (who is initiating the action) and the object (which is the target of the action). The SELinux type (the third part of an SELinux context) of a process (called the domain) is the basis of the fine-grained access controls of that process with respect to itself and other types (which can be processes, files, sockets, network interfaces, and more). The fourth part of an SELinux context, the sensitivity, is not always present (some Linux distributions, by default, do not enable sensitivity labels, but most do). This part of the label is needed for the multilevel security (MLS) support within SELinux, which is an optional setting. Sensitivity labels allow the classification of resources and the restriction of access to those resources based on a security clearance. These labels consist of two parts: a confidentiality value (prefixed with s) and a category value (prefixed with c).

Label and context are often used interchangeably, and although there is a technical distinction (one is a representation of the other)

SELinux developers decided to use labels instead of real process and file (or other resource) metadata for its access controls. This is different from MAC systems such as AppArmor, which uses the path of the binary (and thus the process name) and the paths of the resources to handle permission checks.

SELinux’s enforcing mode assumes a role akin to an unyielding guardian, allowing only actions that align with meticulously defined security rules. When operating in enforcing mode, SELinux rigidly enforces access controls and security contexts, thereby confining potentially malicious actions and reducing the likelihood of unauthorized intrusion. This mode ensures that even if an attacker gains access, their ability to maneuver and exploit vulnerabilities is severely curtailed, thereby enhancing the overall resilience of the system to enable enforcing mode.

More than 130 classes and over 250 permissions known to SELinux, policy rules need to take all these classes and permissions into account for each interaction.

Roles

SELinux roles are defined with an _r suffix.

  • user_r role is meant for restricted users. This role is only allowed to have processes with types specific to end-user applications. Privileged types, including those used to switch to another Linux user, are not allowed for this role.
  • staff_r role is meant for non-critical operations. This role is generally restricted to the same applications as the restricted user, but it has the ability to switch roles. It is the default role for operators to have (so as to keep those users in their least privileged role as long as possible).
  • sysadm_r role is meant for system administrators. This role is very privileged, enabling various system administration tasks. However, certain end-user application types might not be supported (especially if those types are used for potentially vulnerable or untrusted software) to keep the system free from infections.
  • secadm_r role is meant for security administrators. This role allows changing the SELinux policy and manipulating the SELinux controls. It is generally used when a separation of duties is needed between system administrators and system policy management.
  • system_r role is meant for daemons and background processes. This role is quite privileged, supporting the various daemon and system process types. However, end-user application types and other administrative types are not allowed in this role.
  • unconfined_r role is meant for end users. This role allows a limited number of types, but those types are very privileged as they allow running any application launched by a user (or another unconfined process) in a more or less unconfined manner (not restricted by SELinux rules). This role, as such, is only available if the system administrator wants to protect certain processes (mostly daemons) while keeping the rest of the system operations almost untouched by SELinux. Other roles might exist, such as guest_r and xguest_r, depending on the distribution.

List roles in system

# seinfo –-role 
Roles: 9
auditadm_r
object_r
secadm_r
…
user_r

switch between permissive mode and enforcing mode

sudo setenforce 1  # enable enforcing mode
sudo setenforce 0  # enable permissive mode
echo 0 > /sys/fs/selinux/enforce

In this mode, SELinux will strictly enforce the defined security policies, denying actions that violate those policies.

verify that SELinux is in enforcing mode

getenforce
sestatus
ls -lZ # nie będzie zwracał etykiet bezpieczeństwa jeśli SELinux jest wyłączony
  • enabled: SELinux jest włączony.
  • disabled: SELinux jest wyłączony.
  • enforcing: Polityki SELinux są aktywnie wymuszane.
  • permissive: Polityki są rejestrowane w logach, ale nie są wymuszane.

Tryby pracy SELinux

SELinux może pracować w trzech trybach:

  • Enforcing: Polityki są aktywnie egzekwowane. Każde naruszenie jest blokowane.
  • Permissive: Polityki są rejestrowane w logach, ale nie są egzekwowane.
  • Disabled: SELinux jest wyłączony.
sudo setenforce 0  # Tryb permissive
sudo setenforce 1  # Tryb enforcing

Aby zmienić tryb pracy na stałe, edytuj plik /etc/selinux/config:

SELINUX=enforcing # Dostępne opcje: enforcing, permissive, disabled

permissive mode

In contrast, SELinux’s permissive mode serves as an insightful observer in the security landscape. When switched to permissive mode, SELinux refrains from blocking actions that breach security policies, but it actively logs these incidents. This mode serves as an essential tool for system administrators seeking to fine-tune their security policies without abruptly disrupting operations. By analyzing the logs generated in permissive mode, administrators can identify potential issues that would arise if the system were operating in enforcing mode. This invaluable feedback loop empowers administrators to iteratively refine security policies, ensuring they strike an optimal balance between stringent security and operational functionality to enable SELinux’s permissive mode:

sudo setenforce 0

Enabling or disabling SELinux Boolean values

SELinux Booleans are configurable options that take on a single value and manipulate parts of the active SELinux policy.The value of the conditionals can be persisted (meaning they survive reboots) or be kept only during the current boot session.

At the heart of SELinux’s configurational arsenal lie Boolean values, encapsulating binary settings that enable or disable specific security features. These Boolean values serve as cryptographic keys that can unlock a multitude of security configurations, allowing administrators to sculpt the behavior of the system with precision.

# setsebool -P secure_mode_policyload on # -P for persist
 getsebool -a

This command is used to display the current values of all SELinux Boolean settings. SELinux Boolean values are binary settings that determine whether a specific security feature or permission is enabled (on) or disabled (off).

$ sudo semanage boolean -l

SELinux boolean                State  Default Description
    (...)
    httpd_enable_cgi               (on   ,   on)  Allow httpd to enable cgi
    httpd_enable_ftp_server        (off  ,  off)  Allow httpd to enable ftp server
    httpd_enable_homedirs          (off  ,  off)  Allow httpd to enable homedirs
    httpd_execmem                  (off  ,  off)  Allow httpd to execmem
    httpd_graceful_shutdown        (off  ,  off)  Allow httpd to graceful shutdown
    httpd_manage_ipa               (off  ,  off)  Allow httpd to manage ipa
    httpd_mod_auth_ntlm_winbind    (off  ,  off)  Allow httpd to mod auth ntlm winbind
    httpd_mod_auth_pam             (off  ,  off)  Allow httpd to mod auth pam
    httpd_read_user_content        (off  ,  off)  Allow httpd to read user content
    httpd_run_ipa                  (off  ,  off)  Allow httpd to run ipa
    (...)

$ getsebool httpd_enable_cgi
   httpd_enable_cgi --> on
$ sudo setsebool httpd_enable_cgi 0
$ getsebool httpd_enable_cgi
   httpd_enable_cgi --> off

  • abrt_anon_write --> off: This indicates that the SELinux Boolean value for allowing the Automatic Bug Reporting Tool (ABRT) to write to anonymous memory is currently disabled.
  • abrt_handle_event --> off: This Boolean value controls whether ABRT can handle events is disabled. ABRT handles system events such as crashes or abnormal terminations.
  • abrt_upload_watch_anon_write --> on: This means that the Boolean value that allows ABRT to watch for uploads with anonymous write access is enabled.
  • antivirus_can_scan_system --> off: This states that the Boolean value that permits antivirus software to scan the entire system is currently disabled.
  • antivirus_use_jit --> off: The Boolean value controlling whether antivirus software can use Just-In-Time (JIT) scanning is disabled.
  • auditadm_exec_content --> on: This indicates that the Boolean value allowing the auditadm user to execute content is enabled.
  • authlogin_nsswitch_use_ldap --> off: The Boolean value that determines whether the authlogin program should use the Network Security Services (NSS) LDAP module is disabled.
  • authlogin_radius --> off: The Boolean value that controls whether the authlogin program can use the radius protocol for authentication is disabled.
  • authlogin_yubikey --> off: This means that the Boolean value permitting the authlogin program to use YubiKey for authentication is disabled.
  • awstats_purge_apache_log_files --> off: The Boolean value that decides whether awstats should be allowed to purge Apache log files is disabled.

Searching for a Boolean and getting its information

semanage boolean -l
getsebool abrt_anon_write # To check the status of a specific SELinux Boolean
semanage boolean -l | grep xguest_connect_network

Enabling a SELinux Boolean value

setsebool -P xguest_use_bluetooth 1  # sets the xguest_use_bluetooth Boolean to on and makes the change permanent across system reboots.

Disabling a SELinux Boolean value

setsebool -P mount_anyfile 0

Kontekst zabezpieczen procesu

ps -eZ
ps -eZ | grep sshd
system_u:system_r:sshd_t:s0-s0:c0.c1023 2629 ? 00:00:00 sshd
  • The SELinux user system_u
  • The SELinux role system_r
  • The SELinux type (also known as the domain when we are looking at a running process) sshd_t
  • The sensitivity level s0-s0:c0.c1023

Kontekst zabezpieczen uzytkownika

id -Z
sysadm_u:sysadm_r:sysadm_t:s0-s0:c0.c1023

Polityki SELinux

Polityki SELinux definiują, jakie operacje są dozwolone dla procesów i użytkowników w systemie.

  • Wyświetlanie zainstalowanych polityk
sudo semanage fcontext -l 
  • Dodawanie nowej reguły polityki Jeśli plik lub katalog wymaga nietypowej etykiety, można dodać regułę:
sudo semanage fcontext -a -t httpd_sys_content_t "/sciezka/do/pliku(/.*)?"

Następnie zastosuj zmiany:

restorecon -R /sciezka/do/pliku
  • Usuwanie reguły polityki:
sudo semanage fcontext -d "/sciezka/do/pliku(/.*)?"
  • Tworzenie niestandardowych polityk - użyj narzędzia audit2allow:
sudo cat /var/log/audit/audit.log | audit2allow -M moja_polityka
sudo semodule -i moja_polityka.pp

Diagnozowanie problemów z SELinux

  • Rejestrowanie zdarzeń - jeśli SELinux blokuje operację, zdarzenie jest rejestrowane w logach systemowych. Aby je przejrzeć:\
sudo cat /var/log/audit/audit.log | grep AVC
  • Narzędzie audit2why pomaga zrozumieć, dlaczego operacja została zablokowana:
sudo cat /var/log/audit/audit.log | audit2why

Logging and auditing

By default, SELinux will send its messages to the Linux audit subsystem. There, the messages are picked up by the Linux audit daemon (auditd) and logged in the /var/log/audit/audit.log file.

Whenever SELinux verifies a particular access, it does not always go over the entire policy. Instead, it has an access vector cache (AVC), in which it stores the results of previous access attempts. This cache ensures that SELinux can quickly react to activities without having a huge impact on performance.

Example:

type=AVC msg=audit(03/22/2020 12:15:38.557:2331): avc:
denied { read } for pid=12569 comm="dmesg"
name="xterm-256color" dev="sdb2" ino=131523
scontext=sysadm_u:sysadm_r:dmesg_t:s0-s0:c0.c1023
tcontext=system_u:object_r:etc_t:s0 tclass=file
permissive=0

When the Linux kernel checks a permission request, this request is represented as an access vector, and the cache is then consulted to quickly find the appropriate response. If the cache has the right access vector, then the decision is taken from the cache; otherwise, the SELinux subsystem consults the policy itself and updates the cache. Of course, SELinux invalidates the cache when a new policy is loaded or the policy is dynamically adjusted. This ensures that all permission checks are in line with the active policy.

Files

obraz

# ls -dZ /srv/web/localhost/htdocs/dokuwiki
undefined_u:object_r:var_t:s0 /srv/web/localhost/htdocs/dokuwiki # context displayed here is var_t.

$ getfattr -m . -d dokuwiki
# file: dokuwiki
security.selinux="unconfined_u:object_r:var_t:s0"

$ stat dokuwiki
File: dokuwiki
Size: 211 Blocks: 0 IO Block: 4096
directory
Device: fd01h/64769d Inode: 8512888 Links: 8
Access: (0755/drwxr-xr-x) Uid: ( 0/ root) Gid: ( 0/ root)
Context: unconfined_u:object_r:var_t:s0
...
Application-specific contexts

PostgreSQL:

  • The postgresql_t context is meant for the application itself (process type or domain).
  • The postgresql_port_t context is meant for the TCP port on which the PostgreSQL daemon listens.
  • The postgresql_server_packet_t and postgresql_client_packet_t contexts are types associated with network packets received (in case of the postgresql_server_packet_t type) or sent to the PostgreSQL port.
  • The postgresql_exec_t type is assigned to the postgres binary.
  • The various postgresql_*_t types for specific filesystem locations related to the daemon, such as postgresql_var_run_t (to apply to resources in /var/run), postgresql_etc_t (to apply to resources in /etc), postgresql_log_t (to apply to resources in /var/log), and postgresql_tmp_t (to apply to resources in /tmp).
  • The mysqld_db_t type for the database files themselves.

Keeping or ignoring contexts

Based on the context of a file or resource, administrators can easily detect anomalies in the system setup. An example of an anomaly is when we move a file from the user's home directory to a web server location. When this occurs, the file retains the user_home_t context as extended attributes are moved with it. As the web server process isn't allowed to access user_home_t by default, it will not be able to serve this file to its users.

How to properly set contexts during such copy or move operations:

Inheriting the default contexts

By default, the SELinux security subsystem uses context inheritance to identify which context should be assigned to a file (or directory, socket, and so on) when it is created. A file created in a directory with a var_t context will be assigned the var_t context as well. This means that the file inherits the context from the parent directory and not from the context of the executing process.

Copying and moving files

File contexts can also be transferred together with the file itself during copy or move operations. By default, Linux will do the following:

  • Retain the file context in case of a move (mv) operation on the same filesystem (as this operation does not touch extended attributes, but merely adjusts the metadata of the file).
  • Ignore the current file context in case of a move operation across a filesystem boundary, as this creates a new file, including content and extended attributes. Instead, it uses the inheritance (or file transition rules) to define the target context.
  • Ignore the file context in case of a copy (cp) operation, instead using the inheritance (or file transition rules) to define the target context.

Use mv with -Z option to tell mv that the context of the file should be set to the default type associated with the target location.

# touch test1 test2
# mv test1 /srv
# mv -Z test2 /srv  # retain current context - admin_home_t
# ls -Z /srv/test*  # take context from /srv directory - var_t 
staff_u:object_r:admin_home_t:s0 /srv/test1
staff_u:object_r:var_t:s0 /srv/test2

Use cp command through the --preserve=context option to preserve the SELinux context while copying files

# cp test1 /srv
# cp --preserve=context test2 /srv
# ls -Z /srv/test*
staff_u:object_r:var_t:s0 /srv/test1
staff_u:object_r:admin_home_t:s0 /srv/test2

Most of the utilities provided through the coreutils package support the -Z option: mkdir (to create a directory), mknod (to create a device file), mkfifo (to create a named pipe), and so on.

the rsync command can preserve the extended attributes by using the -X or --xattrs option.

explicitly provide a context through the --context option

# mkdir --context=user_u:object_r:user_home_t:s0 /srv/foo
# ls -dZ /srv/foo
user_u:object_r:user_home_t:s0 /srv/foo
Zarządzanie kontekstami plików
ls -lZ
-rw-r--r--. 1 user group unconfined_u:object_r:user_home_t:s0 plik.txt

etykieta bezpieczeństwa: unconfined_u:object_r:user_home_t:s0

  • unconfined_u: Kontekst użytkownika (user context). Określa tożsamość użytkownika w systemie bezpieczeństwa.
  • object_r: Typ roli (role type). Określa, do czego plik może być używany (np. jako plik, katalog, itp.).
  • user_home_t: Typ pliku (file type). Określa, do jakiej kategorii plik należy (np. plik domowy, binarny, konfiguracyjny itp.).
  • s0: Poziom wrażliwości (sensitivity level). Stosowane w systemach z wielopoziomowym bezpieczeństwem (np. SELinux).

Do zarządzania kontekstami w SELinux służy polecenie chcon. Możesz również zarządzać etykietami za pomocą narzędzi takich jak restorecon.

chcon -t typ_etykiety plik
chcon -t httpd_sys_content_t /var/www/html/index.html
restorecon -v /var/www/html/index.html  # przywrocenie domyslnych etykiet -v pokazuje szczegoly dzialania
chcon -u unconfined_u plik
chcon -l s0 plik
chcon -R -t httpd_sys_content_t /srv/web # put the httpd_sys_content_t label on these files, which would allow web servers to have read access on these resources
chcon -R --reference /var/www /srv/www   # to label /srv/web and its resources with the same context as used for the /var/www director

If we change the context of a file through chcon and set it to a context different from the one in the context list, then the context might be reverted later: package managers might reset the file contexts back to their intended value, or the system administrator might trigger a fill filesystem relabeling operation.