Ansible on RHEL 10: SELinux and SSH on a New Port

The eighth lab in the Ansible series: one playbook keeps SELinux enforcing, labels a new SSH port, opens it in the firewall and hardens sshd with a drop-in file, then moves SSH off port 22 without locking Ansible out. Includes a port that SELinux silently refused while Ansible reported success, a root login the installer kept allowing because of file order in sshd_config.d, and a playbook that still worked after port 22 was closed, until a minute later.

Goal: the same SELinux and SSH setup on server1 and server2, kept in one playbook:

  • SELinux is enforcing with the targeted policy, and stays that way after a reboot
  • sshd also listens on port 2222, with the SELinux label and firewall rule that port needs
  • root can’t log in over SSH, and nobody can log in with a password
  • in the end, SSH runs only on 2222, and Ansible still reaches both servers

These are the SELinux and SSH tasks from my RHCSA practice exercises.

Starting point: the setup from the earlier labs in this series: server1 is the control node, the project is in ~/ansible, and the ansible user logs in with an SSH key (lab 1). rhel-system-roles is installed (lab 2).

Before you start: take a snapshot of both servers, or keep a console open on them. This lab changes how you log in. A mistake can lock out SSH, and the console is the way back in.

Lab environment:

HostIP addressRole
server1192.168.10.10control node + managed node
server2192.168.10.11managed node

The addresses are examples. Replace them with your own.

Tested on: a CentOS Stream 10 virtual machine with SELinux enforcing (ansible-core 2.16, rhel-system-roles 2.4, OpenSSH 9.9). Containers can’t test SELinux, so for this lab I used a full VM that managed itself over SSH. Every output below comes from that test.

1. Which tool for what

TaskToolIn ansible-core?
SELinux mode, port labelsredhat.rhel_system_roles.selinuxno, but on the ISO
firewallredhat.rhel_system_roles.firewallno, but on the ISO
sshd settingsansible.builtin.copy with validateyes
check what sshd really usescommand: sshd -T + assertyes
check that sshd listensansible.builtin.wait_foryes

ansible.posix.selinux and community.general.seport aren’t available offline. The selinux role does both jobs: it sets the mode in /etc/selinux/config and the running system, and it labels ports with semanage.

2. Variables

In group_vars/servers.yml:

ssh_port: 2222
ssh_keep_port_22: true

ssh_keep_port_22 is for the move in section 7. While it’s true, sshd listens on both ports, so you can’t lock yourself out by testing the new one.

3. The playbook

cd ~/ansible
vim selinux-ssh.yml
---
- name: SELinux and SSH on every server
  hosts: servers
  become: true
  vars:
    selinux_state: enforcing
    selinux_policy: targeted
    selinux_ports:
      - ports: "{{ ssh_port }}"
        proto: tcp
        setype: ssh_port_t
        state: present
    firewall:
      - port: "{{ ssh_port }}/tcp"
        state: enabled
      - service: ssh
        state: "{{ 'enabled' if ssh_keep_port_22 else 'disabled' }}"
  tasks:
    - name: SELinux is enforcing and allows the SSH port
      ansible.builtin.include_role:
        name: redhat.rhel_system_roles.selinux

    - name: The SSH port is open in the firewall
      ansible.builtin.include_role:
        name: redhat.rhel_system_roles.firewall

    - name: sshd settings
      ansible.builtin.copy:
        dest: /etc/ssh/sshd_config.d/00-hardening.conf
        content: |
          {% if ssh_keep_port_22 %}
          Port 22
          {% endif %}
          Port {{ ssh_port }}
          PermitRootLogin no
          PasswordAuthentication no
          MaxAuthTries 3
        mode: "0600"
        validate: /usr/sbin/sshd -t -f %s
      notify: Reload sshd

    - name: Read the settings sshd will use
      ansible.builtin.command: sshd -T
      register: sshd_effective
      changed_when: false

    - name: The settings are the ones we wrote
      ansible.builtin.assert:
        that:
          - "'permitrootlogin no' in sshd_effective.stdout_lines"
          - "'passwordauthentication no' in sshd_effective.stdout_lines"
          - "('port ' ~ ssh_port) in sshd_effective.stdout_lines"
        quiet: true

    - name: Apply the new sshd settings now
      ansible.builtin.meta: flush_handlers

    - name: sshd listens on the new port
      ansible.builtin.wait_for:
        port: "{{ ssh_port }}"
        timeout: 10

  handlers:
    - name: Reload sshd
      ansible.builtin.systemd_service:
        name: sshd
        state: reloaded

How to read it:

  • The order matters. The SELinux label and the firewall come first, and sshd is reloaded last. Section 5 shows what happens when sshd gets the new port before SELinux allows it.
  • selinux_ports does what semanage port -a -t ssh_port_t -p tcp 2222 does by hand. Port 22 already has the label in the default policy.
  • A drop-in file instead of editing sshd_config. /etc/ssh/sshd_config includes every file in /etc/ssh/sshd_config.d/ near its top. A separate file belongs to this playbook alone, and system updates never conflict with it. Section 6 explains the 00- in the name.
  • validate runs sshd -t on the new file before it replaces the old one. A typo fails the task, and the running sshd keeps its old configuration.
  • sshd -T prints the settings sshd actually uses after reading every file. The assert compares them with what we wanted. It catches mistakes that validate can’t see.
  • flush_handlers + wait_for reload sshd in the middle of the play, then check that something listens on the new port. Without this check, a port SELinux refused looks exactly like success (section 5).

4. Run it

ansible-playbook --syntax-check selinux-ssh.yml
ansible-playbook selinux-ssh.yml

The tasks that changed something on the first run:

TASK [redhat.rhel_system_roles.selinux : Set an SELinux label on a port] *******
changed: [server2] => (item={'ports': 2222, 'proto': 'tcp', 'setype': 'ssh_port_t', 'state': 'present'})

TASK [redhat.rhel_system_roles.firewall : Configure firewall] ******************
changed: [server2]

TASK [sshd settings] ***********************************************************
changed: [server2]

RUNNING HANDLER [Reload sshd] **************************************************
changed: [server2]

PLAY RECAP *********************************************************************
server2  : ok=41   changed=6    unreachable=0    failed=0    skipped=35 ...

On my test VM, the firewall role also had to install and start firewalld, which counted as two more changes. On a server installed from the RHEL ISO, firewalld already runs.

The second run:

PLAY RECAP *********************************************************************
server2  : ok=40   changed=0    unreachable=0    failed=0    skipped=35 ...

What ended up on the server:

ansible server2 -b -a "semanage port -l" | grep ^ssh_port_t
ansible server2 -b -a "ss -tlnp" | grep sshd
ssh_port_t                     tcp      2222, 22
LISTEN 0      128          0.0.0.0:2222       0.0.0.0:*    users:(("sshd",...))
LISTEN 0      128          0.0.0.0:22         0.0.0.0:*    users:(("sshd",...))

The key login on the new port works, and the others are refused:

ssh -p 2222 server2 hostname
ssh -p 2222 -o PubkeyAuthentication=no server2
sudo ssh -p 2222 root@server2
server2
ansible@server2: Permission denied (publickey,gssapi-keyex,gssapi-with-mic).
root@server2: Permission denied (publickey,gssapi-keyex,gssapi-with-mic).

password isn’t in the list of methods any more, so sshd doesn’t even ask for one. Root was refused although it had a valid key.

5. The port SELinux refused

The first version of the playbook had only the sshd settings task, without the SELinux role. Ansible reported success, and sshd was running:

PLAY RECAP *********************************************************************
server2  : ok=3    changed=2    unreachable=0    failed=0    skipped=0 ...
active

But it was only listening on port 22:

LISTEN 0      128          0.0.0.0:22         0.0.0.0:*    users:(("sshd",...))
LISTEN 0      128             [::]:22            [::]:*    users:(("sshd",...))

The sshd log said why:

journalctl -u sshd -n 5
error: Bind to port 2222 on 0.0.0.0 failed: Permission denied.
error: Bind to port 2222 on :: failed: Permission denied.
Server listening on 0.0.0.0 port 22.

And the audit log said who:

grep denied /var/log/audit/audit.log | grep name_bind
avc:  denied  { name_bind } for  pid=1160 comm="sshd" src=2222 scontext=system_u:system_r:sshd_t:s0-s0:c0.c1023 tcontext=system_u:object_r:unreserved_port_t:s0 tclass=tcp_socket permissive=0

sshd runs as sshd_t, and SELinux only lets it bind ports labelled ssh_port_t. Port 2222 was unreserved_port_t. sshd doesn’t stop when one port fails. It keeps the ports it got, so systemctl shows it as active and Ansible sees a successful reload.

That’s why the playbook ends with wait_for on the new port. With it, this mistake fails the play instead of looking like success.

6. Root could still log in

In the first version, the file was called 50-hardening.conf, like the files RHEL ships in that directory. sshd -t accepted it, but sshd -T showed:

permitrootlogin yes

The directory had another file that sets the same option:

ls /etc/ssh/sshd_config.d/
cat /etc/ssh/sshd_config.d/01-permitrootlogin.conf
01-permitrootlogin.conf  10-acceptenv-colorterm.conf  40-redhat-crypto-policies.conf  50-cloud-init.conf  50-hardening.conf  50-redhat.conf
PermitRootLogin yes

The RHEL installer writes 01-permitrootlogin.conf when you tick Allow root SSH login with password on the root password screen. My test VM came from a cloud image, not the installer, so I created that file myself, with the same content, to see what it does. sshd reads the files in alphabetical order, and for most settings the first value wins. 01- comes before 50-, so PermitRootLogin no in my file was ignored. That’s the opposite of most config directories, where the last file wins.

Hence the name 00-hardening.conf: it’s read first, so its values win. The assert task catches this too. With the file renamed back to 50-hardening.conf, the play stopped:

fatal: [server2]: FAILED! => {"assertion": "'permitrootlogin no' in sshd_effective.stdout_lines", "changed": false, "evaluated_to": false, "msg": "Assertion failed"}

To check your own servers:

ansible all -b -a "ls /etc/ssh/sshd_config.d/"

7. Moving SSH off port 22

When ssh -p 2222 works on both servers, port 22 can go. Two things have to change together: sshd and the firewall stop using 22, and Ansible starts connecting to 2222. Both go in group_vars/servers.yml:

ssh_port: 2222
ssh_keep_port_22: false
ansible_port: 2222

ansible_port is the port Ansible connects to. It’s a normal variable, so it can live in group_vars with the rest.

The first time, I set only ssh_keep_port_22: false and forgot ansible_port. The run succeeded:

PLAY RECAP *********************************************************************
server2  : ok=41   changed=3    unreachable=0    failed=0    skipped=35 ...

sshd now listened on 2222 only, and the firewall no longer allowed ssh:

0.0.0.0:2222
[::]:2222
cockpit dhcpv6-client

I ran the playbook again right away, and it also succeeded, with changed=0, although Ansible was still connecting to port 22. A minute later:

fatal: [server2]: UNREACHABLE! => {"changed": false, "msg": "Failed to connect to the host via ssh: ssh: connect to host 127.0.0.1 port 22: Connection refused", "unreachable": true}

Ansible keeps its SSH connection open for 60 seconds after a run (ControlPersist=60s), so the next run can reuse it. A reload doesn’t close connections that are already open, so the old connection on port 22 kept working. A run right after the change proves nothing. Wait more than a minute, or check with a new connection, ssh -p 2222 server2.

With ansible_port: 2222 in the same file, the next run connected again:

PLAY RECAP *********************************************************************
server2  : ok=40   changed=0    unreachable=0    failed=0    skipped=35 ...

You also connect by hand on the new port, ssh -p 2222 server2. To avoid typing it, add this to ~/.ssh/config on server1:

Host server1 server2
    Port 2222

Verification

From ~/ansible on server1, after the move to 2222:

ansible all -a "getenforce"                                  # Enforcing
ansible all -b -a "semanage port -l" | grep ^ssh_port_t      # 2222, 22
ansible all -b -a "ss -tlnp" | grep sshd                     # :2222 only
ansible all -b -a "firewall-cmd --list-ports"                # 2222/tcp
ansible all -b -a "sshd -T" | grep -E "^(port|permitrootlogin|passwordauthentication) "
ssh -p 2222 server2 hostname                                 # server2
ansible-playbook selinux-ssh.yml                             # changed=0 on both

Wait a minute after the last change before you trust the result, and then run the playbook again (section 7).

Safety notes

  • Keep a console or a snapshot ready. A wrong SSH change locks you out, and only the console gets you back in.
  • Move SSH in two runs. First add the new port next to 22 and test it. Only then remove 22 and set ansible_port.
  • Label the port in SELinux before sshd uses it. Otherwise sshd skips the port, and nothing fails.
  • Check with sshd -T, not only sshd -t. -t checks the syntax. -T shows which value won.
  • Name your drop-in so it’s read first. In sshd_config.d, the first value wins.
  • Don’t trust a run right after a port change. Ansible’s open connection hides the problem for a minute.
  • Don’t turn SELinux off to make something work. Find the denial in /var/log/audit/audit.log and fix the label, as in section 5.