Logo

How to Configure SELinux on CentOS 7

Mar 30, 2024

To configure SELinux on CentOS 7, follow the steps below:

Step 1 : By default, SELinux is enabled. You can check its status using the following command:

getenforce

Step 2 : You can also check the SELinux configuration using:

sestatus

Step 3 : SELinux has three modes: Enforcing, Permissive, and Disabled.

- Enforcing: SELinux security policy is enforced.

- Permissive: SELinux does not enforce security policy but logs actions that would be denied in enforcing mode.

- Disabled: SELinux is completely disabled.

Step 4 : Disable SELinux.

If you don't need SELinux for any reason, you can disable it temporarily or permanently:

- Temporarily disable SELinux:

setenforce 0

- Permanently disable SELinux: Edit the SELINUX line in /etc/selinux/config file to:

SELINUX=disabled

- Reboot the system if SELinux is disabled permanently.

Step 5 : Check the SELinux status again to ensure it's disabled if that was your intention.

Step 6 : Basic SELinux Configuration

- For a basic example, let's install Apache:

sudo yum install httpd

Step 7 : Edit the Apache configuration file:

sudo nano /etc/httpd/conf/httpd.conf

Add the line Listen 8001 to change the default port.

Listen 8001

Step 8 : Create a configuration file:

sudo nano /etc/httpd/conf.d/example.conf

Add configuration to change port and root folder.

<VirtualHost *:8001>
    ServerAdmin webmaster@example.com
    ServerName example.com
    DocumentRoot /home/example.com

    <Directory "/home/example.com">
        AllowOverride All
        Require all granted
    </Directory>
</VirtualHost>

Step 9 : Create a folder and index file:

mkdir /home/example.com
echo "<h2>example.com</h2>" > /home/example.com/index.html

Step 10 : Set appropriate permissions

sudo chown -R apache:apache /home/example.com
sudo chmod -R 755 /home/example.com

Step 11 : Open firewall port if necessary:

sudo firewall-cmd --add-port=8001/tcp --permanent
sudo firewall-cmd --reload

Step 11 : Install policycoreutils-python:

sudo yum install policycoreutils-python

Step 12 : List SELinux port contexts:

sudo semanage port -l | grep -w http_port_t

Step 13 : Add a new port for Apache:

sudo semanage port -a -t http_port_t -p tcp 8001

Step 14 : Verify the port addition:

sudo semanage port -l | grep -w http_port_t

Step 15 : Use matchpathcon to compare new directory with default Apache directory:

matchpathcon /var/www/html /home/example.com

Step 16 :Match SELinux contexts for the new directory:

sudo semanage fcontext -a -t httpd_sys_rw_content_t "/home/example.com(/.*)?"

Step 17 : Apply the label changes:

sudo restorecon -R -v /home/example.com/

Step 18 : Test the Apache configuration:

sudo apachectl configtest

Step 19 : Restart Apache:

sudo systemctl restart httpd

Step 20 : Test the configuration by accessing domain:port.

Congratulations! Your SELinux configuration on CentOS 7 is complete.