Configure SELinux mandatory access controls for enhanced security

Intermediate 45 min May 07, 2026 57 views
Ubuntu 24.04 Debian 12 AlmaLinux 9 Rocky Linux 9

Set up SELinux on Ubuntu and Debian systems, configure security modes and policies, create custom application rules, and implement comprehensive monitoring for enhanced Linux security hardening.

Prerequisites

  • Root or sudo access
  • Basic understanding of Linux file permissions
  • Familiarity with systemd services

What this solves

SELinux (Security-Enhanced Linux) provides mandatory access controls that enforce security policies at the kernel level, preventing unauthorized access even from compromised applications. This tutorial covers installing SELinux on Ubuntu and Debian systems, configuring security modes, creating custom policies for applications, and monitoring policy violations for comprehensive system hardening.

Step-by-step installation

Update system packages

Start by updating your package manager to ensure you get the latest security updates and package versions.

sudo apt update && sudo apt upgrade -y
sudo dnf update -y

Install SELinux packages

Install the core SELinux packages along with policy management tools and utilities for configuration and monitoring.

sudo apt install -y selinux-basics selinux-policy-default auditd policycoreutils-python-utils setools-console
sudo dnf install -y selinux-policy selinux-policy-targeted policycoreutils-python-utils setools-console audit

Configure SELinux activation

On Ubuntu and Debian systems, SELinux needs to be explicitly activated. Configure the system to enable SELinux on next boot.

sudo selinux-activate
sudo selinux-config-enforcing

Configure SELinux main configuration

Set the SELinux configuration file to define the default policy and enforcement mode. The targeted policy provides good security without being overly restrictive.

# This file controls the state of SELinux on the system.

SELINUX= can take one of these three values:

enforcing - SELinux security policy is enforced.

permissive - SELinux prints warnings instead of enforcing.

disabled - No SELinux policy is loaded.

SELINUX=enforcing

SELINUXTYPE= can take one of these values:

targeted - Targeted processes are protected,

minimum - Modification of targeted policy. Only selected processes are protected.

mls - Multi Level Security protection.

SELINUXtype=targeted

Enable audit daemon

The audit daemon logs SELinux events and policy violations, which is essential for monitoring and troubleshooting.

sudo systemctl enable auditd
sudo systemctl start auditd

Reboot and verify SELinux status

SELinux requires a system reboot to initialize properly. After rebooting, verify the installation and current status.

sudo reboot

After the system reboots, check SELinux status:

sestatus
getenforce

Configure SELinux modes and policies

Understanding SELinux modes

SELinux operates in three modes: enforcing (blocks violations), permissive (logs violations), and disabled. Start with permissive mode to identify potential issues.

sudo setenforce 0
getenforce
Note: Use permissive mode initially to identify applications that need policy adjustments without breaking functionality.

Configure web server policies

Enable SELinux boolean settings for common web server operations. These settings allow HTTP services to function properly under SELinux.

sudo setsebool -P httpd_can_network_connect 1
sudo setsebool -P httpd_can_network_connect_db 1
sudo setsebool -P httpd_execmem 1
sudo setsebool -P httpd_unified 1

Configure SSH service policies

Allow SSH to use non-standard ports and enable key-based authentication features under SELinux.

sudo setsebool -P ssh_sysadm_login 1
sudo semanage port -a -t ssh_port_t -p tcp 2222

Set file contexts for web directories

Configure proper SELinux contexts for web server directories to ensure applications can read and write files as needed.

sudo semanage fcontext -a -t httpd_exec_t "/var/www/html(/.)?"\nusudo semanage fcontext -a -t httpd_log_t "/var/log/nginx(/.)?"\nsudo restorecon -R /var/www/html
sudo restorecon -R /var/log/nginx

Create custom SELinux policies for applications

Generate policy module from audit logs

Use audit2allow to create custom policy modules based on actual application behavior recorded in audit logs.

sudo grep nginx /var/log/audit/audit.log | audit2allow -m nginx_custom
sudo grep nginx /var/log/audit/audit.log | audit2allow -M nginx_custom

Create custom application policy

Create a Type Enforcement (.te) file for a custom application that needs specific permissions.

policy_module(myapp, 1.0)

type myapp_t;
type myapp_exec_t;
domain_type(myapp_t)
domain_entry_file(myapp_t, myapp_exec_t)

type myapp_log_t;
logging_log_file(myapp_log_t)

type myapp_config_t;
files_config_file(myapp_config_t)

Allow myapp to read its configuration

allow myapp_t myapp_config_t:file { read getattr open };

Allow myapp to write to its log files

allow myapp_t myapp_log_t:file { create write append getattr setattr }; allow myapp_t myapp_log_t:dir { add_name write };

Allow network access

corenet_tcp_bind_generic_node(myapp_t) corenet_tcp_bind_http_port(myapp_t)

Compile and install custom policy

Compile the Type Enforcement file into a policy module and install it into the SELinux policy store.

cd /tmp
sudo checkmodule -M -m -o myapp.mod myapp.te
sudo semodule_package -o myapp.pp -m myapp.mod
sudo semodule -i myapp.pp

Set file contexts for custom application

Define and apply SELinux contexts for your custom application files, logs, and configuration directories.

sudo semanage fcontext -a -t myapp_exec_t "/usr/local/bin/myapp"
sudo semanage fcontext -a -t myapp_config_t "/etc/myapp(/.)?"\nsudo semanage fcontext -a -t myapp_log_t "/var/log/myapp(/.)?"\nsudo restorecon -R /usr/local/bin/myapp
sudo restorecon -R /etc/myapp
sudo restorecon -R /var/log/myapp

Monitor and troubleshoot SELinux denials

Configure audit log monitoring

Set up automatic monitoring of SELinux denials using audit daemon and log rotation for ongoing security monitoring.

# Monitor SELinux denials and policy changes
-w /etc/selinux/ -p wa -k selinux_policy
-w /usr/sbin/setenforce -p x -k selinux_enforce
-a always,exit -F arch=b64 -S execve -F key=selinux_exec

Create SELinux monitoring script

Create a script to parse audit logs and identify SELinux denials with actionable recommendations.

#!/bin/bash

SELinux Denial Monitor Script

LOGFILE="/var/log/audit/audit.log" OUTPUT_FILE="/var/log/selinux-denials.log" echo "SELinux Denial Report - $(date)" > $OUTPUT_FILE echo "=========================================" >> $OUTPUT_FILE

Extract recent denials

ausearch -m avc -ts recent 2>/dev/null | audit2allow -a >> $OUTPUT_FILE 2>/dev/null

Count denials by type

echo "\nDenial Summary:" >> $OUTPUT_FILE grep "type=AVC" $LOGFILE | awk '{for(i=1;i<=NF;i++) if($i~/scontext/) print $i}' | sort | uniq -c | sort -nr >> $OUTPUT_FILE

Email report if denials found

if [ -s $OUTPUT_FILE ]; then echo "SELinux denials detected. Check $OUTPUT_FILE for details." # mail -s "SELinux Denial Report" admin@example.com < $OUTPUT_FILE fi
sudo chmod +x /usr/local/bin/selinux-monitor.sh

Set up automated monitoring with cron

Schedule regular SELinux monitoring and create a systemd service for continuous monitoring.

echo "0 /6    /usr/local/bin/selinux-monitor.sh" | sudo crontab -

Configure SELinux troubleshooting tools

Install and configure additional tools for SELinux analysis and troubleshooting common policy issues.

sudo apt install -y setroubleshoot-server python3-audit
sudo dnf install -y setroubleshoot-server python3-audit

Enable enforcing mode

After testing and resolving policy issues in permissive mode, enable enforcing mode for full security protection.

sudo setenforce 1
echo 'SELINUX=enforcing' | sudo tee /etc/selinux/config
Warning: Only enable enforcing mode after thorough testing in permissive mode. Enforcing mode will block unauthorized actions immediately.

Verify your setup

sestatus -v
getenforce
sudo semodule -l | head -10
ps auxZ | grep -E "(httpd|nginx|ssh)" | head -5
sudo ausearch -m avc -ts recent

The output should show SELinux as enabled and enforcing, with loaded policy modules and running processes showing proper security contexts. If you see any recent AVC denials, investigate them using the monitoring tools configured above.

For ongoing integration with your security infrastructure, consider connecting to OSSEC intrusion detection systems or setting up comprehensive CIS benchmark compliance across your infrastructure.

Common issues

SymptomCauseFix
Web server returns 403 errorsIncorrect file contextssudo restorecon -R /var/www and check contexts with ls -Z
Application cannot write logsMissing write permissions in policyUse audit2allow to generate policy from denials
SSH connection refusedSELinux blocking non-standard portsudo semanage port -a -t ssh_port_t -p tcp PORT
Database connection failsMissing network connect booleansudo setsebool -P httpd_can_network_connect_db 1
Custom application crashesMissing domain transitionsCreate proper .te policy with domain_entry_file rules
Policy module load failsSyntax errors in .te fileCheck with checkmodule and review audit logs

Next steps

Running this in production?

Need this managed? Setting up SELinux once is straightforward. Keeping policies updated, monitoring violations, and managing custom rules across environments is the harder part. See how we run infrastructure like this for European teams with comprehensive security compliance requirements.

Automated install script

Run this to automate the entire setup

Need help?

Don't want to manage this yourself?

We handle infrastructure security hardening for businesses that depend on uptime. From initial setup to ongoing operations.