How to Allow a Hostname Reverse DNS in hosts.deny

hosts.denyssh

I wish to BLOCK all sshd connection BUT one dynamic IP assigned to a <subdomain>.ddns.net so I've put this in /etc/hosts.deny:

sshd: ALL EXCEPT <subdomain>.ddns.net

This does not allow me to connect to SSH.
Instead, if I place the IP resolved (a dig <subdomain>.ddns.net confirms it) by that hostname, it works:

sshd: ALL EXCEPT <ipv4.resolved.by.hostname>

I've also tried with UseDNS yes or no in sshd_config, but it changes nothing.

Firewall (UFW) is open by the rule ufw limit ssh

My actual /etc/ssh/sshd_config here below:

Protocol 2
HostKey /etc/ssh/ssh_host_rsa_key
HostKey /etc/ssh/ssh_host_ed25519_key
KexAlgorithms curve25519-sha256@libssh.org
Ciphers chacha20-poly1305@openssh.com,aes256-gcm@openssh.com,aes128-gcm@openssh.com,aes256-ctr,aes192-ctr,aes128-ctr
MACs hmac-sha2-512-etm@openssh.com,hmac-sha2-256-etm@openssh.com,umac-128-etm@openssh.com,hmac-sha2-512,hmac-sha2-256,umac-128@openssh.com
PermitRootLogin no
AllowUsers remotessh
IgnoreRhosts yes
PasswordAuthentication no
PermitEmptyPasswords no
ChallengeResponseAuthentication no
UsePAM yes
X11Forwarding no
PrintMotd no
PubkeyAuthentication yes
AllowTcpForwarding no
AllowStreamLocalForwarding no
GatewayPorts no
PermitTunnel no
UseDNS no

# Allow client to pass locale environment variables
AcceptEnv LANG LC_*

# override default of no subsystems
Subsystem       sftp    /usr/lib/openssh/sftp-server

Best Answer

The problem is most likely due to the fact that the ip address that you are connecting from reverses to xxx.yourisp.com, not subdomain.ddns.net.

When you attempt to connect to sshd from your (dynamic) ip address, tcpwrappers does a reverse dns lookup on your ip address. If this resolves to xxx.yourisp.com, then it won't find the match in hosts.allow or (hosts.deny as it may), and therefore it won't allow the connection to sshd from your ip.

As a workaround, you might want to consider adding subdomain.ddns.net to your /etc/hosts file, and create a cron job that runs every few minutes and updates this entry with your dynamic ip address whenever it changes. It's not a very elegant solution, but it's the best I could come up with when I recently faced this problem myself. If anyone knows of a cleaner solution, please comment.