preface

Security-enhanced Linux (SELinux) is a Linux kernel module and a Security subsystem of Linux.

SELinux was developed primarily by the U.S. National Security Agency. The SELinux module has been integrated with Linux kernels 2.6 and above.

The structure and configuration of SELinux is very complex, and there are a lot of conceptual things that can be difficult to master. Many Linux system administrators have bothered to turn SELinux off.

If I can master SELinux and use it correctly, I think the system is basically “unbreakable” (always remember that there is no absolute security).

Mastering the basic concepts of SELinux and simple configuration methods is a must for every Linux system administrator.

1. Basic Concepts

1. Security context of TE model

All operating system access controls are based on subjects, objects, and the access control attributes associated with them.

In Selinux, the ** access control property is called the security context. ** All objects (files, interprocess communication channels, sockets, network hosts, etc.) and principals (processes) have a security context associated with them.

** A security context contains three elements: ** Users, roles, and Type identifiers.

** The security context is in the following form: **user: role: type

** For processes: ** indicates user, role, and type identifiers respectively. Also known as domains

** For objects: ** The first two items have little practical use, role is usually object_r, and user is usually the user of the process that created the object, and has no effect on access control

Conclusion:

SELinux is managed by Mandatory Access Control (MAC). The subject of SELinux Control is the process and the target is the file resources that can be accessed by the process.

The main body

SELinux is primarily about managing control processes.

Note * : For ease of understanding, processes are treated as subjects below unless otherwise specified.

The target

The “target resource” that the principal process can access is typically the file system.

object

The resource accessed by the principal. It can be a file, directory, port, device, etc.

Note * : For ease of understanding, files or directories are treated as objects below unless otherwise specified.

strategy

Because of the large number of processes and files, SELiunx sets basic access security policies based on certain services.

There are detailed rules within these policies that specify whether or not different services open access to certain resources.

There are usually a large number of files and processes in the system, and to save time and cost, we usually just selectively control some processes.

Policy determines which processes need to be regulated and how.

There are multiple rules in a set of policies. Some rules can be enabled or disabled as required (this type of rule is referred to as a Boolean rule below).

Rules are modular and extensible. When a new application is installed, the application can add rules by adding new modules. Users can also manually add or subtract rules.

SELINUX parameter values:

enforcing: enforce SELinux.

Permissive: displays warning messages only.

Disabled: Disables the SELinux function.

SELINUXTYPE parameter value:

Targeted: The default policy has more restrictions on network services and less restrictions on the local host.

Strict: indicates a complete protection function, including network services, general commands, and applications, which is strictly restricted.

Security context

The security context is at the heart of SELinux.

Security context I myself divide it into “process security context” and “file security context”.

One process security context generally corresponds to multiple file security contexts.

A process can access files only when the two security contexts match. Their correspondence is determined by the rules in the policy.

The file security context is determined by where the file is created and the process that created the file. And the system has a set of default values, users can also set the default value.

It is important to note that simply moving a file does not change the security context of the file.

The structure and meaning of a security context

The security context has four fields, separated by colons. System_u :object_r:admin_home_t:s0.

How SELinux works

SELinux works in three modes:

enforcing: mandatory mode. Violations of SELinux rules are blocked and logged.

Permissive: permissive mode. Violations of SELinux rules are only logged. Generally used for debugging.

Disabled: Disables SELinux.

The SELinux working mode can be set in /etc/selinux/config.

To switch from disabled to enforcing or permissive, restart the system. And vice versa.

Enforcing and permissive mode can quickly switch by a command setenforce 1 | 0.

Note that if your system has been running with SELinux off for some time, the first restart after SELinux is turned on May be slow. Because the system must create a security context for the files on disk.

SELinux logging requires the auditd.service service, do not disable it.

SELinux workflow

Display the security context

Add -z to show the subject and object context

Ls-z displays the security context of the file system

Ps-z displays the security context of the process

Id-z displays the shell security context: Joe: usr_r: usr_t

2. TE access control

In SELinux, there are no allowed rules and no superusers by default. The allowed access must be given by the rule.

One rule is as follows:

allow Source type(s) Target type(s): Object class(es) Permission(s)

For example, access rules like this:

allow user_t bin_t : file {read execute getattr};

Indicates that processes whose domain is user_t are allowed to read, execute, and obtain attributes from files whose type is bin_t

3. The role

SELinux also provides role-based access control

Specify the role type with the following statement:

role user_r type passwd_t;

Without the above statement, then:

The security context Joe: user_r: passwd_t cannot be created

The exec call fails, even if the policy permits it

Second, architecture,

1. Kernel architecture

Based on Linux Security Module (LSM), it provides mandatory access control for all kernel resources

Note * : LSM (Linux Security Module) is a lightweight security access control framework. It mainly uses Hook functions to control access permissions and has transparent security attributes built into some objects.

LSM provides a series of hook functions

If access is denied by the DAC, the audit results will be affected

SELinux’s architecture is as follows:

Policy decisions are contained in the secure server, architecture-independent and portable

The object manager is the manager of objects and, in the LSM architecture, is a series of LSM hooks that are distributed throughout the subsystems of the kernel.

Note * : The Interface provided by the Linux security module (LSM) is the hook. It is initialized to point to virtual functions that implement the default traditional UNIX superuser mechanism. Module writers must re-implement these hook functions to satisfy their security policies.

2. Object manager for user space

SELinux supports putting object managers into user mode, using the kernel’s object management Policy server to manage objects in user mode

However, object managers that support user space have some weaknesses:

For TE models, you also need to define classes

The administrative policy for the object manager is no longer in the kernel

The policy service architecture is as follows:

AVC stands for various caches

SELinux functions and rights management mechanism

1 The role of SELinux

The main purpose of SELinux is to minimize the number of resources available to the server processes in the system (the minimum permission rule).

Imagine if a web service running as root had a 0day vulnerability that could be exploited by a hacker to do whatever he wanted on your server as root. Isn’t it scary?

SELinux is designed to solve this problem.

2 DAC

On operating systems that do not use SELinux, what determines whether a resource can be accessed is whether a resource has the corresponding user’s permissions (read, write, execute).

The process accessing the resource can be accessed as long as it meets the above conditions.

The most deadly problem is that the root user is unregulated and has unlimited access to any resource on the system.

The subject of this permission management mechanism is the user, also known as autonomous access control (DAC).

3 MAC

In addition to the above factors, determining whether a resource can be accessed on an operating system using SELinux requires determining whether each type of process has access to a particular type of resource.

In this way, even if the process is running as root, you need to determine the type of the process and the type of resources it is allowed to access before deciding whether to allow access to a resource. The activity space of the process can also be compressed to a minimum.

Even a server running as root can generally access only the resources it needs. Even if a program is compromised, the impact is limited to the resources it allows access to. Security is greatly increased.

The subject of this permission management mechanism is the process, also known as forced access control (MAC).

The MAC is divided into two modes, one is called category security (MCS) mode and the other is called Multi-level security (MLS) mode.

The following operations are in MCS mode.

4 Comparison of DAC and MAC

Here is a picture to illustrate.

As you can see, in DAC mode, as long as the corresponding directory has the corresponding user’s permission, it can be accessed. In MAC mode, the process is also limited by the number of directories it can access.

Basic SELinux operations

1 Query the security context of a file or directory

Basic Usage of commands

Ls-z displays the security context of the file system

Ps-z displays the security context of the process

Id-z displays the shell security context: Joe: usr_r: usr_t

Usage, for example,

Example Query the security context of /etc/hosts.

ls -Z /etc/hosts

The execution result

[root@localhost ~]# ls -Z /etc/hosts -rw-r--r--. root root system_u:object_r:net_conf_t:s0 /etc/hosts [root@localhost ~] #Copy the code

2 Query the security context of the process

Basic Usage of commands

Ps auxZ | grep -v grep | grep process of < name >

Usage, for example,

Query the security context of nginx-related processes.

ps auxZ | grep -v grep | grep sshd

The execution result

[root@localhost ~]# [root@localhost ~]# ps auxZ | grep -v grep | grep sshd system_u:system_r:sshd_t:s0-s0:c0.c1023 root 1454 0.0 0.0 112940 4324? Ss Sep03 0:00 /usr/sbin/sshd -d unconfined_u:unconfined_r:unconfined_t:s0-s0:c0.c1023 root 11664 0.0 0.0 158944 5596? Ss 10:340:00 SSHD: root@pts/0 unconfined_u:unconfined_r:unconfined_t:s0-s0:c0.c1023 root 11668 0.0 0.0 156812 5444? Ss 10:34 0:00 sshd: root@notty [root@localhost ~]#Copy the code

3 Manually change the security context of a file or directory

Basic Usage of commands

Chcon < options > < File or directory 1> [< file or directory 2>…

Usage, for example,

Change the security context of test to system_u:object_r:httpd_sys_content_t:s0.

chcon -u system_u -r object_r -t httpd_sys_content_t html2/* [root@localhost nginx]# ls -Z drwxr-xr-x. root root system_u:object_r:httpd_sys_content_t:s0 html drwxr-xr-x. root root unconfined_u:object_r:usr_t:s0 html2 [root@localhost  nginx]# ls -Z html2 -rw-r--r--. root root unconfined_u:object_r:usr_t:s0 404.html -rw-r--r--. root root unconfined_u:object_r:usr_t:s0 50x.html -rwxr-xr-x. root root unconfined_u:object_r:usr_t:s0 index.html -rw-r--r--. root  root unconfined_u:object_r:usr_t:s0 nginx-logo.png -rw-r--r--. root root unconfined_u:object_r:usr_t:s0 poweredby.png [root@localhost nginx]# chcon -u system_u -r object_r -t httpd_sys_content_t html2/* [root@localhost nginx]# ls -Z html2  -rw-r--r--. root root system_u:object_r:httpd_sys_content_t:s0 404.html -rw-r--r--. root root system_u:object_r:httpd_sys_content_t:s0 50x.html -rwxr-xr-x. root root system_u:object_r:httpd_sys_content_t:s0 index.html -rw-r--r--. root root system_u:object_r:httpd_sys_content_t:s0 nginx-logo.png -rw-r--r--. root root system_u:object_r:httpd_sys_content_t:s0 poweredby.png [root@localhost nginx]#Copy the code

4 Restore the security context of the file or directory to the default value

Basic Usage of commands

Restorecon [options] < file or directory 1> [< file or directory 2>…

Usage, for example,

After adding some web files to the directory on the Nginx server, set up the correct security context for these new files.

[root@localhost ~]# 
[root@localhost ~]# restorecon -R /root/test/
[root@localhost ~]# 
[root@localhost ~]# ls -Z 
-rw-------. root root system_u:object_r:admin_home_t:s0 anaconda-ks.cfg
drwxr-xr-x. root root unconfined_u:object_r:admin_home_t:s0 test
[root@localhost ~]# 


Copy the code

5 Query the status of Boolean rules in the system

Basic Usage of commands

getsebool -a

Since this command queries either all rules or only one rule, it is common to query all rules first and then grep filtering.

Usage, for example,

Query for Boolean rules associated with HTTPD.

getsebool -a | grep ssh

The execution result

[root@localhost ~]# 
[root@localhost ~]# getsebool -a | grep ssh
fenced_can_ssh --> off
selinuxuser_use_ssh_chroot --> off
ssh_chroot_rw_homedirs --> off
ssh_keysign --> off
ssh_sysadm_login --> off
[root@localhost ~]#


Copy the code

Switch a Boolean rule

Basic Usage of commands

Setsebool [option] rules of < name > < on | off >

Usage, for example,

Enable the httpD_anon_write rule.

setsebool -P httpd_anon_write on

The execution result

[root@localhost ~]#  getsebool -a | grep ssh
fenced_can_ssh --> off
selinuxuser_use_ssh_chroot --> off
ssh_chroot_rw_homedirs --> off
ssh_keysign --> off
ssh_sysadm_login --> off
[root@localhost ~]# 
[root@localhost ~]# 
Copy the code

Modify Boolean rules

[root@localhost ~]# setsebool -P ssh_sysadm_login on

[root@localhost ~]# 
[root@localhost ~]#  getsebool -a | grep ssh
fenced_can_ssh --> off
selinuxuser_use_ssh_chroot --> off
ssh_chroot_rw_homedirs --> off
ssh_keysign --> off
ssh_sysadm_login --> on
[root@localhost ~]# 
[root@localhost ~]# setsebool -P ssh_sysadm_login off
[root@localhost ~]# 
[root@localhost ~]#  getsebool -a | grep ssh
fenced_can_ssh --> off
selinuxuser_use_ssh_chroot --> off
ssh_chroot_rw_homedirs --> off
ssh_keysign --> off
ssh_sysadm_login --> off
[root@localhost ~]# 


Copy the code

The configuration file directory is the content of the file

[root@localhost booleans]# pwd
/sys/fs/selinux/booleans
[root@localhost booleans]# cat mpd_use_cifs
0 0
Copy the code

7 Add a default security context for the directory

Basic Usage of commands

(Install the PolicyCoreutils-Python package if you are prompted to find the command, same as below.)

Semanage fContext -a -t < Type field in file security context > “< directory (without slash) >(/.*)?”

Note: The default security context of a directory or file can be queried using the semanage fcontext -l command together with grep filtering.

Usage, for example,

After you add a new web directory /usr/share/nginx/html2 for Nginx, you need to set the same default security context as the original directory.

semanage fcontext -a -t httpd_sys_content_t ” /usr/share/nginx/html2(/.*)?”

8 Add a port that certain processes can access

Basic Usage of commands

Semanage port -a -t < service type > -p < protocol > < port number >

Note: You can run the semanage port -l command together with grep to check port numbers supported by various service types.

Usage, for example,

Port 10080 is required for THE HTTP service for Nginx.

semanage port -a -t http_port_t -p tcp 10080

9 Modify the parameters by referring to other parameters

Basic Usage of commands

Chcon –reference=< source >

Modify the 1. TXT file

[root@localhost html]# ll -Z -rw-r--r--. root root unconfined_u:object_r:usr_t:s0 1.txt -rw-r--r--. root root system_u:object_r:httpd_sys_content_t:s0 404.html -rw-r--r--. root root system_u:object_r:httpd_sys_content_t:s0 50x.html lrwxrwxrwx. root root system_u:object_r:httpd_sys_content_t:s0 en-US -> .. /.. /doc/HTML/en-US drwxr-xr-x. root root system_u:object_r:httpd_sys_content_t:s0 icons lrwxrwxrwx. root root system_u:object_r:httpd_sys_content_t:s0 img -> .. /.. /doc/HTML/img lrwxrwxrwx. root root system_u:object_r:httpd_sys_content_t:s0 index.html -> .. /.. /doc/HTML/index.h -rw-r--r--. root root system_u:object_r:httpd_sys_content_t:s0 nginx-logo.png lrwxrwxrwx. root root system_u:object_r:httpd_sys_content_t:s0 poweredby.png -> nginx-logo.pngCopy the code

The execution result

[root@localhost html]# chcon --reference=404.html 1.txt [root@localhost html]# [root@localhost html]# [root@localhost html]# ll -Z -rw-r--r--. root root system_u:object_r:httpd_sys_content_t:s0 1.txt -rw-r--r--. root root system_u:object_r:httpd_sys_content_t:s0 404.html -rw-r--r--. root root system_u:object_r:httpd_sys_content_t:s0 50x.html lrwxrwxrwx. root root system_u:object_r:httpd_sys_content_t:s0 en-US -> .. /.. /doc/HTML/en-US drwxr-xr-x. root root system_u:object_r:httpd_sys_content_t:s0 icons lrwxrwxrwx. root root system_u:object_r:httpd_sys_content_t:s0 img -> .. /.. /doc/HTML/img lrwxrwxrwx. root root system_u:object_r:httpd_sys_content_t:s0 index.html -> .. /.. /doc/HTML/index.html -rw-r--r--. root root system_u:object_r:httpd_sys_content_t:s0 nginx-logo.png lrwxrwxrwx. root root  system_u:object_r:httpd_sys_content_t:s0 poweredby.png -> nginx-logo.pngCopy the code

10 Restore the new rights to the original

Basic Usage of commands

Restorecon -v < file >

[root@localhost files]# ls -Z /etc/yum.conf 
-rw-r--r--. root root system_u:object_r:etc_t:s0       /etc/yum.conf
[root@localhost files]# 
[root@localhost files]# 
[root@localhost files]# chcon -t httpd_config_t /etc/yum.conf
[root@localhost files]# 
[root@localhost files]# ls -Z /etc/yum.conf 
-rw-r--r--. root root system_u:object_r:httpd_config_t:s0 /etc/yum.conf
[root@localhost files]# 
Copy the code

The execution result

[root@localhost files]# restorecon -v /etc/yum.conf 
restorecon reset /etc/yum.conf context system_u:object_r:httpd_config_t:s0->system_u:object_r:etc_t:s0
[root@localhost files]# ls -Z /etc/yum.conf 
-rw-r--r--. root root system_u:object_r:etc_t:s0       /etc/yum.conf
[root@localhost files]# 
Copy the code

11 Check identity and role similarity

[root@localhost ~]# yum install setools-console [root@localhost ~]# seinfo [options] -r: Lists all roles in SELinux. -t: lists all types in SELinux. -b: Lists all Boolean values (that is, the names of the specific rules in the policy). -x: Displays more information.Copy the code

5. SELinux error analysis and resolution

1 Learn about SELinux logs

When SELinux is enabled, normal behavior of many services is considered a violation (errors in the title and below refer to violations).

This is where the SELinux violation log comes in.

SELinux violation logs are saved in /var/log/audit/audit.log.

The content of /var/log/audit/audit.log looks something like this.

. [root@localhost ~]# tailf /var/log/audit/audit.log type=GRP_MGMT MSG =audit(1630901844.207:878): pid=11979 uid=0 auid=0 ses=76 subj=unconfined_u:unconfined_r:groupadd_t:s0-s0:c0.c1023 msg='op=add-shadow-group id=994 exe="/usr/sbin/groupadd" hostname=? addr=? terminal=? Res = success 'type = ADD_USER MSG = audit (1630901844.247-879). pid=11984 uid=0 auid=0 ses=76 subj=unconfined_u:unconfined_r:useradd_t:s0-s0:c0.c1023 msg='op=add-user id=997 exe="/usr/sbin/useradd" hostname=? addr=? terminal=? Res = success 'type = USER_MGMT MSG = audit (1630901844.288-880). pid=11989 uid=0 auid=0 ses=76 subj=unconfined_u:unconfined_r:useradd_t:s0-s0:c0.c1023 msg='op=pam_tally2 reset=0 id=997 exe="/usr/sbin/pam_tally2" hostname=? addr=? terminal=? Res = success 'type = SOFTWARE_UPDATE MSG = audit (1630901844.314-881). pid=11968 uid=0 auid=0 ses=76 subj=unconfined_u:unconfined_r:unconfined_t:s0-s0:c0.c1023 MSG ='sw="nginx-filesystem-1:1.20.1-2.el7.noarch" sw_type= RPM key_enforce=0 gpg_res=1 root_dir="/" comm="yum" Exe = "/ usr/bin/python2.7" hostname = localhost. Localdomain addr =? Terminal = PTS / 0 = success 'res type = SOFTWARE_UPDATE MSG = audit (1630901844.581-882) : pid=11968 uid=0 auid=0 ses=76 subj=unconfined_u:unconfined_r:unconfined_t:s0-s0:c0.c1023 MSG ='sw="nginx-1:1.20.1-2.el7.x86_64" sw_type= RPM key_enforce=0 gpG_res =1 root_dir="/" comm="yum" Exe = "/ usr/bin/python2.7" hostname = localhost. Localdomain addr =? Terminal = PTS / 0 = success 'res type = USER_AVC MSG = audit (1630904068.840-883) : pid=1053 uid=81 auid=4294967295 ses=4294967295 subj=system_u:system_r:system_dbusd_t:s0-s0:c0.c1023 msg='avc: received policyload notice (seqno=7) exe="/usr/bin/dbus-daemon" sauid=81 hostname=? addr=? terminal=? 'type = MAC_POLICY_LOAD MSG = audit (1630904065.495-884) : Policy loaded auid=0 SES =76 type=SYSCALL MSG =audit(1630904065.495:884): arch=c000003e syscall=1 success=yes exit=3881672 a0=4 a1=7f3cf9ca2000 a2=3b3ac8 a3=7ffd6fe646a0 items=0 ppid=12014 pid=12019 auid=0 uid=0 gid=0 euid=0 suid=0 fsuid=0 egid=0 sgid=0 fsgid=0 tty=pts0 ses=76 comm="load_policy" exe="/usr/sbin/load_policy" subj=unconfined_u:unconfined_r:unconfined_t:s0-s0:c0.c1023 key=(null) type=PROCTITLE MSG = audit (1630904065.495-884) : proctitle = "/ sbin/load_policy type =" USER_MAC_CONFIG_CHANGE MSG = audit (1630904068.901-885). pid=12014 uid=0 auid=0 ses=76 subj=unconfined_u:unconfined_r:unconfined_t:s0-s0:c0.c1023 msg='resrc=port op=add Lport =10080 proto=6 tcontext=system_u:object_r:http_port_t:s0 comm="semanage" exe="/usr/bin/python2.7" hostname=? addr=? terminal=? res=success'Copy the code

This file is extensive and is mixed with many system audit logs unrelated to SELinux errors. We’ll use the sealert utility to help with this analysis (install setroubleshoot if the command is not found).

2 Use seAlert to analyze errors

Basic Usage of commands

sealert -a /var/log/audit/audit.log

After the command is executed, the system takes a period of time to analyze violations in logs and produce analysis reports. The structure of the analysis report is shown below:

[root@localhost ~]# yum install setroubleshoot-server python3-pydbus
Copy the code

3 SELinux is wrong

When detecting a service error, please check the seAlert analysis report for the keyword of the service process name. If not, the error is not caused by SELinux, please check other aspects.

The default permission for the file directory is file_context

/etc/selinux/targeted/contexts/files/

The next step is to read seAlert’s analysis.

The first thing you need to know is why. Be careful if the reason for the violation includes files or resources that the service should not access. The service configuration may be incorrect or the service itself may have vulnerabilities. Check the service configuration file first.

There are usually 2-3 solutions to a violation in an analysis report. Choose a solution that is easy to understand, such as changing Boolean values and setting the default security context.

If you don’t have a simple, easy-to-understand solution, check the search engines for better alternatives.

It should be noted that reliability is only a reference value and does not necessarily mean that the solution with the highest reliability can solve the problem. My personal feeling is that the more reliable a solution is, the less it will change the system.

Remember, however, that before implementing the solution, it is important to understand what the commands in the solution are!

Finally, use the audit2allow command with caution. The effect of this command is very simple: it forces the error encountered to be allowed and then encapsulated into a SELinux module, which SELinux then loads to eliminate the error. Use Audit2allow is not recommended as a last resort.

This article uses the article synchronization assistant to synchronize