SELinux (Security-Enhanced Linux) is a vital security feature in RHEL 8 that enforces mandatory access control (MAC). This guide demonstrates how to automate the installation and configuration of SELinux using Ansible.

Why Enable SELinux?

SELinux provides enhanced security by restricting access based on policies. It prevents unauthorized access and mitigates security risks.

Key Benefits of SELinux:

  • Mandatory Access Control (MAC): Restricts access based on predefined security policies.
  • Process Isolation: Prevents unauthorized processes from accessing sensitive resources.
  • Enhanced Security: Reduces the attack surface in enterprise environments.

Prerequisites

Before running the Ansible playbook, ensure:

1. You have a control node with Ansible installed.

2. The target system (RHEL 8) is accessible via SSH.

3. You have sudo/root privileges on the target machine.

Writing an Ansible Playbook to Install SELinux

1. Installing SELinux Packages

We need to ensure that the necessary SELinux packages are installed on the target system.

``yaml

  • name: Ensure SELinux packages are installed

yum:

name:

- libselinux

- libselinux-utils

- libsemanage

- policycoreutils

- policycoreutils-python-utils

state: present

`

2. Configuring SELinux Mode

The SELinux configuration file (/etc/selinux/config) needs to be modified to set the mode to enforcing.

`yaml

  • name: Ensure SELinux is set to enforcing

lineinfile:

path: /etc/selinux/config

regexp: '^SELINUX='

line: 'SELINUX=enforcing'

backup: yes

`

3. Checking Current SELinux Status

Before enabling SELinux, check its current mode.

`yaml

  • name: Get current SELinux mode

command: getenforce

register: selinux_mode

changed_when: false

ignore_errors: true

`

4. Enabling SELinux if Not Already Enforcing

If SELinux is not in enforcing mode, we enable it dynamically.

`yaml

  • name: Enable SELinux enforcing mode if not already enabled

command: setenforce 1

when: selinux_mode.stdout != "Enforcing"

ignore_errors: true

`

5. Rebooting the System if SELinux Was Disabled

If SELinux was disabled, the system needs a reboot to fully enable it.

`yaml

  • name: Reboot system if SELinux was disabled

reboot:

when: selinux_mode.stdout == "Disabled"

`

Full Ansible Playbook

Save the following playbook as install_selinux.yml:

``yaml

---

  • name: Install and Enable SELinux on RHEL 8

hosts: all

become: yes

tasks:

- name: Ensure SELinux packages are installed

yum:

name:

- libselinux

- libselinux-utils

- libsemanage

- policycoreutils

- policycoreutils-python-utils

state: present

- name: Ensure SELinux is set to enforcing in config

lineinfile:

path: /etc/selinux/config

regexp: '^SELINUX='

line: 'SELINUX=enforcing'

backup: yes