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 [email protected]
Ciphers [email protected],[email protected],[email protected],aes256-ctr,aes192-ctr,aes128-ctr
MACs [email protected],[email protected],[email protected],hmac-sha2-512,hmac-sha2-256,[email protected]
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
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.
You'll use both
/etc/hosts.allow
and/etc/hosts.deny
to accomplish that. At/etc/hosts.allow
, put the following:At /etc/hosts.deny, insert the following content:
It will work because
/etc/hosts.allow
overlaps/etc/hosts.deny
. But there's a catch: if your server is behind a hairpin NAT (some also call it a NAT reflection), some connections will appear with your gateway's internal IP address to your server, so it might be hard to block.Another option is to use iptables, like that:
Just be aware that iptables takes in account the order of its rules.
Good luck.
I am using a script to make a domain list to an ip list and include it to hosts.allow
The description is here:
https://serverfault.com/a/1105670/974219