How do I block port 22 to prevent incoming ssh on Ubuntu?

I'm trying to block port 22 to disallow incoming ssh connections on a Ubuntu VM. I have issued the command:

$> iptables -A INPUT -p tcp -dport 22 -s ###.##.##.## -j DROP

But I can still ssh into the VM. nmap reports that port 22 is still open.

How do I block port 22 to prevent incoming ssh?


Solution 1:

The thing to remember is that firewall rules are checked in the order they are listed. The kernel will stop processing the chain when a rule is triggered that will either allow or dis-allow a packet or connection.

I think the most common mistake for novice firewall administrators is that they follow the correct instructions to open or block a new connection, such as the one one you did and then discover that it won't take effect.

The reason for that is that the -A option adds that new rule, after all existing rules and you probably have a higher priority existing rule that allows SSH.

Use -I to insert your new rules as the first in the chain and they will not be negated by existing rules, or rather , always look at your complete firewall config

See also Debugging iptables and common firewall pitfalls?