tencent cloud

TencentOS Server

SELinux User Guide

다운로드
포커스 모드
폰트 크기
마지막 업데이트 시간: 2026-10-19 17:22:49
AI 번역
Traditional Linux and SELinux use different permission control mechanisms.
Traditional Linux (Discretionary Access Control, DAC): Read, write, and execute permissions are controlled based on three identity categories: the owner, group, and others of a file or directory.
SELinux (Mandatory Access Control, MAC): SELinux policy rules determine whether a process can access a specific file or directory.
SELinux intercepts all system calls that reach the kernel and denies them by default, allowing them only when an allow rule exists in the policy. Therefore, on a system with SELinux enabled but no policy configured, services may fail to work properly, and administrators need to write rules and add them to the policy. Because policy rules are numerous, they are usually divided into multiple modules so that they can be enabled or disabled separately by system component.
On a system with SELinux enabled, both processes and files are assigned a security context, which serves as the basis for access control decisions. A security context contains tag information such as the SELinux user, role, type, and category.

Security Context

Note: You need to enable SELinux before you can run the following commands.
You can perform the following operations to view the security contexts of the root directory itself, files in the directory, and processes separately:
View the security context of the root directory itself:
ls -Zd /
# system_u:object_r:root_t:s0 /
View the security context of files in the root directory:
ls -Z /
# system_u:object_r:bin_t:s0 bin
# system_u:object_r:boot_t:s0 boot
# system_u:object_r:default_t:s0 data
View the process context:
ps -Zaux | grep systemd-udevd
# system_u:system_r:udev_t:s0-s0:c0.c1023 root 565 0.0 0.1 36964 15172 ? Ss Mar17 0:01 /usr/lib/systemd/systemd-udevd
In the security context, fields are separated by colons (:), and the meaning of each field is as follows:
Field
Description
system_u
SELinux user
object_r
Role
root_t
Type
s0
Sensitivity level

SELinux Users

Each Linux user is mapped to an SELinux user through the SELinux policy. This allows Linux users to inherit the restrictions placed on the SELinux user. The mapped SELinux user identity is used in the SELinux context of processes in that session to define the roles and levels they can enter.

Roles

SELinux uses the Role-Based Access Control (RBAC) security model. It is mainly used to indicate whether the data represents a process or a file or directory. There are two common roles: object_r (representing a file or directory) and system_r (representing a process).

Types

The type field is the most important field in a security context. Whether a process can access a file mainly depends on whether the type field in the process's security context matches the type field in the file's security context. If they match, access is allowed.
Note:
The type field is called type in the security context of a file or directory, but it is called domain in the security context of a process.

Sensitivity Levels

Level is an attribute of MLS and MCS. An MLS range is a pair of levels. If the levels are different, it is written as lowlevel-highlevel. If the levels are the same, it is written as s0 (same as sensitivity). Each level is a sensitivity-category pair, and the category is optional. If a category is present, the level is written as sensitivity:category-set. If no category is present, it is written as sensitivity.

Installing the SELinux Toolkit

In TencentOS Server, SELinux is set to enforcing mode by default and uses the targeted policy. In addition, SELinux-related packages are installed by default in a full installation unless you manually exclude them during the installation process. The list of packages and their functions is described as follows:
policycoreutils: provides utilities for operating and managing SELinux, such as restorecon, setfiles, semodule, load_policy, and setsebool.
selinux-policy: provides configuration for the SELinux reference policy. SELinux Policy is a complete SELinux policy and serves as the basis for other policies such as targeted. This software package contains the selinux-policy.conf file and RPM macros.
selinux-policy-targeted: provides the SELinux targeted policy.
libselinux: provides APIs for SELinux applications.
libselinux-utils: provides utilities such as avcstat, getenforce, getsebool, matchpathcon, selinuxconlist, selinuxdefcon, selinuxenabled, and setenforce.
In addition to the software packages installed by default above, you may need SELinux packages beyond the default installation scope when using SELinux, including but not limited to:
selinux-policy-devel: provides utilities for creating custom SELinux policies and policy modules.
selinux-policy-doc: provides man pages that describe how to configure SELinux and its services.
selinux-policy-mls: provides the MLS (Multi-Level Security) SELinux policy.
setroubleshoot-server: converts denial messages generated when SELinux denies access into detailed descriptions that can be viewed using the sealert utility, which is also provided in this package.
setools-console: provides utilities and libraries for analyzing and querying policies, audit log monitoring and reporting, and file context management.
For the above packages, you can install them according to your needs using the following command:
# Install a package
sudo dnf install <package>

# View installed packages
rpm -q <package>

Installing SELinux Policies

SELinux provides three policies, namely targeted (default), minimum, and mls. Different policy types set different access rules and even SELinux contexts, which directly affect whether the corresponding subject (process) can access the target (file or directory resource).

targeted Policy

The targeted policy mainly performs access control on service processes in the system, and it can also limit other processes and users. Service processes are placed in a sandbox, where they are strictly restricted to prevent malicious attacks launched through such processes from affecting other services or the Linux system.
A sandbox is an environment in which processes can run, but access to other processes or resources is strictly controlled. In other words, each process in a sandbox runs only within its own domain (the area where a process runs is called a domain), and it cannot access other processes or resources unless granted special permissions.
By using this policy, print servers, file servers, web servers, or other services can be shared more securely while reducing the risk of adverse effects on other resources in the system caused by accessing these services.

minimum Policy

The minimum policy was originally created for low-memory computers or devices, such as smartphones. In essence, minimum is similar to targeted, except that it uses only a basic policy rule package. For low-memory devices, the minimum policy allows SELinux to run without consuming excessive resources.

MLS Policy

The MLS policy controls all processes in the system. After enabling MLS, users will encounter errors even if they run the simplest commands, such as ls.
During use, you can run the sestatus command to view the SELinux policy type. The following is an example:
sestatus
# SELinux status: enabled
# SELinuxfs mount: /sys/fs/selinux
# SELinux root directory: /etc/selinux
# Loaded policy name: targeted # Current policy type
# Current mode: enforcing # The current running mode is enforcing mode

SELinux Configuration and Enablement

SELinux configuration is modified through the /etc/selinux/config file, which controls the SELinux working mode and policy type.
SELinux implements three working modes, and different SELinux modes have different characteristics:
enforcing mode: SELinux is enabled and all security policy rules are enforced. Access actions that do not comply with policy rules are denied and logged.
permissive mode: SELinux is enabled, but security policy rules are not enforced. Access actions that do not comply with policy rules are not denied, but are simply logged.
disabled mode: The policy is not loaded at system startup, so policy rules are not accessed, but SELinux is not completely disabled. To completely disable SELinux, set selinux=0 on the kernel command line.

Viewing Work Modes

The working mode of SELinux can be viewed concisely using the getenforce command. If you need to obtain more information, you can run the sestatus command to view it.
getenforce
# Enforcing

Setting Work Modes

The setenforce command can conveniently switch between permissive and enforcing modes, but it cannot switch to disabled mode.
# Switch to permissive mode
setenforce 0

# Switch to enforcing mode
setenforce 1
You can freely switch among the disabled, permissive, and enforcing modes by editing the /etc/selinux/config configuration file.
Note:
SELinux does not label files in disabled mode, and labels may not be applied correctly in permissive mode. After the system is switched to enforcing mode, MAC relies on correct file labels. Therefore, if file label exceptions occur when the system is switched back to enforcing mode, run the following commands in permissive mode to relabel and repair:
fixfiles -F onboot
reboot

SELinux Viewing and Management

After SELinux is installed, it defaults to enforcing mode. In this mode, various policy rules, user mappings, file labels, and others can be viewed and configured as needed. Some common commands for viewing and management are introduced below:

seinfo

SELinux works in targeted mode by default and includes numerous policy rules. You can run the seinfo command to query which specific rules are included.
seinfo -b
# Conditional Booleans: 247
# allow_domain_fd_use
# allow_ftpd_full_access
# ...

getsebool / setsebool

After you query the rule name, you can further use the getsebool/setsebool command to view or set the enablement status of the rule.
# View all Boolean values
getsebool -a

# View a specific Boolean value
getsebool httpd_can_network_connect

# Set a Boolean value (temporary)
setsebool httpd_can_network_connect on

# Set a Boolean value (permanent, written to policy)
setsebool -P httpd_can_network_connect on

sesearch

You can use the seinfo command to query the names of related policy rules. However, to view the specific content of a rule, you need to use the sesearch command.
# View all allowed rules
sesearch --allow
# allow NetworkManager_dispatcher_ddclient_t init_t:service status;
# allow NetworkManager_dispatcher_ddclient_t init_t:system status;
# allow NetworkManager_dispatcher_ddclient_t init_t:unix_stream_socket sendto;

semanage

semanage is a powerful command that includes, but is not limited to, SELinux user query, user management, mapping query, rule query, context query, and more.
# View the mapping between login accounts and SELinux users
sudo semanage login -l

# View the mapping between SELinux users and roles
sudo semanage user -l

# Query rules (Boolean values)
sudo semanage boolean -l

# Query security context.
sudo semanage fcontext -l

SELinux Boolean Management

SELinux Booleans are switches in the policy that allow you to modify policy behavior at runtime without rewriting or reloading the policy. By adjusting Booleans, you can quickly enable or disable certain SELinux policy rules.

Viewing Booleans

Use the getsebool command to view the current Boolean status:
# View all Boolean values and their statuses
getsebool -a

# View a specific Boolean value
getsebool httpd_can_network_connect
# httpd_can_network_connect --> off
You can use semanage boolean -l to view detailed descriptions of Booleans, including their default and current values:
sudo semanage boolean -l | grep httpd
# httpd_can_network_connect (off , off) Allow httpd to network connect
# httpd_can_network_connect_db (off , off) Allow httpd to network connect db
# httpd_enable_cgi (on , on) Allow httpd to enable cgi

Setting Booleans

Use the setsebool command to set Boolean values:
# Temporary setting (invalid after restart)
setsebool httpd_can_network_connect on

# Permanent setting (written to the policy file and still effective after restart)
setsebool -P httpd_can_network_connect on
Note:
Using the -P option writes the modification to the policy file, which may take a few seconds. Without -P, the change takes effect only for the current runtime and reverts to the default after a restart.

Common Boolean Examples

Boolean
Description
httpd_can_network_connect
Allows httpd to initiate network connections.
httpd_can_network_connect_db
Allows httpd to connect to database ports.
httpd_enable_cgi
Allows httpd to execute CGI scripts.
httpd_read_user_content
Allows httpd to read user home directory content.
httpd_unified
Allows httpd to uniformly access all httpd-type files.
ftp_home_dir
Allows vsftpd to access user home directories.
nfs_export_all_rw
Allows read-write access to NFS shares.
samba_enable_home_dirs
Allows Samba to share user home directories.
ssh_sysadm_login
Allows sshd to directly log in as sysadm_t.
use_nfs_home_dirs
Allows use of NFS-mounted home directories.

Modifying Security Contexts

The SELinux security context can be modified in multiple ways, including temporary and permanent modifications.

Temporary Modification with chcon

The chcon command is used to temporarily modify the security context of a file or directory. This modification is reverted to the default value after the file system is relabeled or restorecon is executed.
# Change the file type
chcon -t httpd_sys_content_t /var/www/html/index.html

# Recursively change the type of a directory and its subfiles
chcon -R -t httpd_sys_content_t /var/www/html/

# Change the complete context of a file (user:role:type)
chcon system_u:object_r:httpd_sys_content_t:s0 /var/www/html/index.html

# View the modification result
ls -Z /var/www/html/index.html
# system_u:object_r:httpd_sys_content_t:s0 /var/www/html/index.html

Restoring Default Contexts with restorecon

The restorecon command is used to restore the security context of a file or directory to the default value defined in the policy.
# Restore the default context of a single file
restorecon -v /var/www/html/index.html

# Recursively restore the default context of all files in a directory
restorecon -Rv /var/www/html/

# Force relabeling (ignore existing labels)
restorecon -R -F /var/www/html/

Permanent Modification with semanage fcontext

The semanage fcontext command is used to permanently modify the default security context of a file or directory. After the modification, you need to run restorecon for it to take effect.
# Add a new file context rule
sudo semanage fcontext -a -t httpd_sys_content_t "/custom/web(/.*)?"

# Modify an existing file context rule
sudo semanage fcontext -m -t httpd_sys_content_t "/custom/web(/.*)?"

# Make the rules take effect
restorecon -Rv /custom/web/

# View custom file context rules
sudo semanage fcontext -l | grep /custom/web

# Delete a file context rule
sudo semanage fcontext -d "/custom/web(/.*)?"
Note:
Rules added by semanage fcontext are stored in the policy file under the /etc/selinux/targeted/contexts/files/ directory and remain effective after a restart. Path matching uses regular expressions, and (/.*)? matches the directory and all of its subcontent.

Policy Module Management

The SELinux policy consists of multiple modules, each responsible for a portion of the rules. You can manage these policy modules by using the semodule command.

Viewing Installed Modules

# List all installed modules
semodule -l

# View the number of modules
semodule -l | wc -l

Installing Policy Modules

# Install a policy module
sudo semodule -i mymodule.pp

Removing Policy Modules

# Remove a policy module
sudo semodule -r mymodule

Other Common Operations

# Upgrade a policy module
sudo semodule -u mymodule.pp

# Reload all modules
sudo semodule -R

# Build and install modules (with semodule_compile)
# Typically, use checkmodule and semodule_package to compile .te files first.
checkmodule -M -m -o mymodule.mod mymodule.te
semodule_package -o mymodule.pp -m mymodule.mod
sudo semodule -i mymodule.pp
Note:
Writing a custom policy module typically starts with a .te (Type Enforcement) file, which is then compiled into a .mod file by checkmodule, packaged into a .pp file by semodule_package, and finally installed by using semodule -i.

SELinux Troubleshooting

When SELinux denies an access request from a process, an AVC (Access Vector Cache) denial message is generated. You can troubleshoot SELinux-related issues by using the following tools and logs.

Viewing Audit Logs

SELinux denial messages are recorded in the audit log by default:
# View AVC denial messages in the audit log
sudo ausearch -m AVC -ts recent

# Monitor AVC denial messages in real time
sudo tail -f /var/log/audit/audit.log | grep AVC

# Use ausearch to view recent SELinux denials
sudo ausearch -m AVC,USER_AVC -ts today

sealert Command

The sealert command (provided by the setroubleshoot-server package) converts AVC denial messages into human-readable detailed descriptions and provides remediation suggestions:
# Analyze the audit log and generate a detailed report
sudo sealert -a /var/log/audit/audit.log

# Analyze a single AVC message
sudo sealert -l <message_id>
Example output of sealert:
SELinux is preventing /usr/sbin/httpd from name_connect access on the tcp_socket.

***** Plugin catchall_boolean (89.3 confidence) suggests ********************

If you want to allow httpd to network connect
Then you must tell SELinux about this by enabling the 'httpd_can_network_connect' boolean.

Do
setsebool -P httpd_can_network_connect 1

setroubleshoot Service

The setroubleshoot service continuously monitors the audit log, converts SELinux denial messages into detailed descriptions, and sends them to the system log and DBus:
# Check the setroubleshoot service status
sudo systemctl status setroubleshoot

# Start the service and enable it to start on boot.
sudo systemctl enable --now setroubleshoot

# View messages generated by setroubleshoot
sudo journalctl -t setroubleshoot

Common Troubleshooting Process

# 1. Check the current SELinux status
getenforce
sestatus

# 2. View recent AVC denial messages
sudo ausearch -m AVC -ts recent

# 3. Use sealert to analyze and obtain remediation suggestions
sudo sealert -a /var/log/audit/audit.log

# 4. If you determine that access needs to be allowed, follow the sealert recommendations.
# Setting a Boolean value
setsebool -P <boolean_name> on

# Or modify the file context
sudo semanage fcontext -a -t <type> "<path>(/.*)?"
restorecon -Rv <path>

Real-World Examples

Scenario 1: Custom SSH Port

When you need to change the SSH service port from the default 22 to another port (such as 2222), SELinux prevents sshd from listening on the non-standard port, so you need to add a port tag.
Note:
After sshd is restarted, the original port 22 will no longer accept connections. Before restarting, ensure that the port tag has been added and the firewall has allowed the new port. Keep the current session open, and after the restart, verify that an SSH connection can be established through the new port before disconnecting the current session.
1. Modify the sshd configuration file and change Port 22 to Port 2222:
sudo vi /etc/ssh/sshd_config
2. View the current ssh port tag:
sudo semanage port -l | grep ssh
Output example:
ssh_port_t tcp 22
3. Add an SELinux port tag for the new port:
sudo semanage port -a -t ssh_port_t -p tcp 2222
4. Verify that the port tag has been added:
sudo semanage port -l | grep ssh
Output example:
ssh_port_t tcp 2222, 22
5. Restart the sshd service (no output is returned on success):
sudo systemctl restart sshd
6. Verify that sshd is listening normally:
sudo ss -tlnp | grep sshd
Note:
If the new port already has other types of tags, use -m (modify) instead of -a (add).

Scenario 2: Modifying Web Service Directory Tags

When a web server (such as httpd/nginx) uses a non-default directory (such as /custom/web) as the website root directory, SELinux blocks the web service from accessing that directory. You need to set the correct security context for it.
1. Create a custom Web directory (no output is returned on success):
sudo mkdir -p /custom/web
2. View the current security context:
ls -Zd /custom/web
Output example:
unconfined_u:object_r:default_t:s0 /custom/web
3. Add a permanent file context rule:
sudo semanage fcontext -a -t httpd_sys_content_t "/custom/web(/.*)?"
4. Apply the context rule:
sudo restorecon -Rv /custom/web/
5. Verify that the context has been modified:
ls -Zd /custom/web
Output example:
system_u:object_r:httpd_sys_content_t:s0 /custom/web
6. Modify the web server configuration to point to the new directory by changing DocumentRoot "/var/www/html" to DocumentRoot "/custom/web":
sudo vi /etc/httpd/conf/httpd.conf
7. Restart the httpd service (no output is returned on success):
sudo systemctl restart httpd
8. Verify that the Web service is accessible:
curl http://localhost/

Scenario 3: Allowing Web Services to Connect to Databases

When a Web application needs to connect to a remote database, SELinux blocks httpd from initiating network connections by default. You need to enable the corresponding Boolean.
1. View the Boolean values related to httpd:
getsebool -a | grep httpd_can_network
2. Enable the httpd network connection Boolean (the -P option makes it persistent):
setsebool -P httpd_can_network_connect on
3. If you are connecting to a database, enable the database connection Boolean:
setsebool -P httpd_can_network_connect_db on
4. Verify that the Boolean is enabled:
getsebool httpd_can_network_connect
Output example:
httpd_can_network_connect --> on
5. Restart the Web service for the configuration to take effect (no output is returned on success):
sudo systemctl restart httpd

Scenario 4: Allowing NFS Shared Home Directory Access

When you mount a home directory over NFS, SELinux blocks access to NFS files by default. You need to enable the corresponding Boolean.
1. View the current NFS-related Boolean values:
getsebool -a | grep nfs
2. Enable the NFS home directory access Boolean (the -P option makes it persistent):
setsebool -P use_nfs_home_dirs on
3. Verify the Boolean:
getsebool use_nfs_home_dirs
Output example:
use_nfs_home_dirs --> on
4. Mount the NFS home directory:
sudo mount -t nfs nfs-server:/home /home
5. Verify that the home directory is accessible:
ls -Z /home/user/

Scenario 5: Temporarily Switching to permissive Mode for Troubleshooting

If a service fails to work properly due to SELinux denial, you can first switch to permissive mode to verify whether the issue is caused by SELinux.
1. View the current mode:
getenforce
Output example:
Enforcing
2. Switch to permissive mode (no output is returned on success):
setenforce 0
3. Reproduce the issue and check whether there are AVC denial records:
sudo ausearch -m AVC -ts recent
4. Use sealert to analyze the denial reason:
sudo sealert -a /var/log/audit/audit.log
5. Based on the sealert recommendations, set the corresponding Boolean values or contexts. To set a Boolean value:
setsebool -P <boolean_name> on
Or modify the file context (replace <type> and <path> with the actual type and path):
sudo semanage fcontext -a -t <type> "<path>(/.*)?"
sudo restorecon -Rv <path>
6. Switch back to enforcing mode (no output is returned on success):
setenforce 1
7. Restart the service and verify that it resumes normal operation (replace <service> with the actual service name):
sudo systemctl restart <service>


도움말 및 지원

문제 해결에 도움이 되었나요?

피드백