🔐
Security

SELinux

Security-Enhanced Linux mandatory access control for RHEL, CentOS, and Fedora

🐧 Linux🍎 Mac🪟 Windows
Reviewed: Tested on: Kubernetes 1.29 · Terraform 1.8 · Ubuntu 22.04

What is this?

SELinux adds an extra security layer on Linux that controls which programs can access which files.

📥

Step 01

Install / Enable SELinux

(01)SELinux is pre-installed on RHEL-based systems

Linux
1# Check if installed
2rpm -q libselinux selinux-policy
3sestatus
4
5# Ubuntu (optional):
6sudo apt-get install -y selinux-basics selinux-policy-default
7sudo selinux-activate # requires reboot
⚙️

Step 02

Configure SELinux

(01)Set operating mode

Linux
1# Check current mode
2getenforce # Enforcing, Permissive, or Disabled
3sestatus
4
5# Temporary change
6sudo setenforce 0 # Permissive (logs but doesn't block)
7sudo setenforce 1 # Enforcing
8
9# Permanent — edit /etc/selinux/config:
10# SELINUX=enforcing
11# SELINUXTYPE=targeted
12# Reboot required for Disabled → Enabling

(02)File contexts and booleans

Linux
1# View file context
2ls -Z /var/www/html/
3ps auxZ | grep httpd
4
5# Restore default context
6sudo restorecon -Rv /var/www/html/
7
8# Change context type
9sudo semanage fcontext -a -t httpd_sys_content_t "/web(/.*)?"
10sudo restorecon -Rv /web
11
12# Boolean settings
13getsebool -a | grep httpd
14sudo setsebool -P httpd_can_network_connect on

(03)Troubleshoot denials

Linux
1# View AVC denials
2sudo ausearch -m avc -ts recent
3sudo sealert -a /var/log/audit/audit.log
4
5# Generate custom policy from denial
6sudo ausearch -m avc -c 'httpd' --raw | audit2allow -M myhttpd
7sudo semodule -i myhttpd.pp
8
9# audit2why for explanation
10sudo ausearch -m avc -ts recent | audit2why

Step 03

Verify SELinux

(01)Check status and policies

Linux
1sestatus
2semodule -l | head
3sesearch --allow -s httpd_t -t httpd_sys_content_t

Step 04

Manage SELinux

(01)Port labeling and policy modules

Linux
1# Allow custom port
2sudo semanage port -a -t http_port_t -p tcp 8080
3sudo semanage port -l | grep http
4
5# Install/remove policy module
6sudo semodule -i mypolicy.pp
7sudo semodule -r mypolicy
8
9# Full relabel (after enable)
10sudo touch /.autorelabel
11sudo reboot