How to filter SSH connections with hosts.allow on Rocky Linux / CentOS 8

How to filter SSH connections with hosts.allow on Rocky Linux / CentOS 8

The TCP Wrappers suite of programs is no longer included in RHEL / CentOS 8, so also Rocky Linux 8, meaning the hosts.allow and hosts.deny files no longer exist, and adding them manually yields no results.

This makes quick filtering of incoming connections by IP address a bit more difficult as it requires being handled using the firewall.

Luckily, the tcp_wrappers package is still available in the EPEL repository even for versions 8, so the previous functionality can be restored, albeit with some additional steps.

The EPEL repository itself is provided as a package in Rocky Linux / CentOS 8 so get started by installing it:

dnf install epel-release

Then continue with tcp_wrappers:

dnf install tcp_wrappers

This is where the procedure gets a bit trickier, since the SSH daemon in release 8 no longer has support for libwrap:

cp /usr/lib/systemd/system/sshd@.service /etc/systemd/system/

Then edit this file /etc/systemd/system/sshd@.service with your favourite editor and replace

ExecStart=-/usr/sbin/sshd -i $OPTIONS $CRYPTO_POLICY

with

ExecStart=@-/usr/sbin/tcpd /usr/sbin/sshd -i $OPTIONS $CRYPTO_POLICY

If SELinux is in enforced state, also run setsebool ssh_use_tcpd on getsebool ssh_use_tcpd ssh_use_tcpd –> on

Finally, swap sshd with the replacement sshd.socket

systemctl stop sshd; systemctl start sshd.socket

Now you can edit the /etc/hosts.allow and /etc/hosts.deny files to create allow/deny lists, for example:

# hosts.allow
sshd: 1.2.3.4/32, 10.0.0.0/8, 192.168.122.0/24

# hosts.deny
sshd: ALL

Once you’re convinced the server is running correctly and accepts connections from where it should and blocks as expected, permanently disable sshd and enable the replacement:

systemctl disable sshd; systemctl enable sshd.socket

Finally, to customize the port SSH connections are accepted on, edit the recently added /usr/lib/systemd/system/sshd.socket and change the ListenStream (port) number to the desired value:


 

Leave a Reply