How to prevent unauthorized ssh login attempts

Solution 1:

By poking around, the bad guys have found out that your external port 54321 is your ssh access port. The ports listed in your log are their source ports, not the destination ports. You should find that ssh login attempts on your port 54321 occur at a much much lower rate than if it were port 22.

You can mitigate the issue via iptables rules, or fail2ban (however it is spelled), or other. I use the recent module in itpables:

# Dynamic Badguy List. Detect and DROP Bad IPs that do password attacks on SSH.
# Once they are on the BADGUY list then DROP all packets from them.
#$IPTABLES -A INPUT -i $EXTIF -m recent --update --hitcount 3 --seconds 5400 --name BADGUY_SSH -j LOG --log-prefix "SSH BAD:" --log-level info
#$IPTABLES -A INPUT -i $EXTIF -m recent --update --hitcount 3 --seconds 5400 --name BADGUY_SSH -j DROP
# Sometimes make the lock time very long. Typically to try to get rid of coordinated attacks from China.
$IPTABLES -A INPUT -i $EXTIF -m recent --mask $BIT_MASK --update --hitcount 3 --seconds 90000 --name BADGUY_SSH -j LOG --log-prefix "SSH BAD:" --log-level info
$IPTABLES -A INPUT -i $EXTIF -m recent --mask $BIT_MASK --update --hitcount 3 --seconds 90000 --name BADGUY_SSH -j DROP
$IPTABLES -A INPUT -i $EXTIF -p tcp -m tcp --dport 22 -m recent --mask $BIT_MASK --set --name BADGUY_SSH -j ACCEPT

I now use a BIT_MASK (currently "255.255.252.0"), because attackers have become clever and often merely switch to another ip address on the same sub-net. $EXTIF is my WAN facing NIC.