It turns out that SSH brute-force attacks, dictionary attacks or combinations of those are daily routines nowadays. Server logs are quickly filled with login attempts, in the hopes that one of them is right. The best prevention against these kind of attacks is to - obviously - have a secure password, or even better to force key-based authentication.
However, this won’t stop automated attacks from trying out dozens of usernames and passwords anyway, which is generally annoying. Thus, the approach to hide the SSH port, which by default is 22. One solution some people do is moving SSH to a non-standard port. Basically, some random number that won’t conflict with anything else.
Another interesting trick is to not immediately expose the SSH port, but only when a client is saying “Open Sesame”. Jokes aside, that’s roughly what port knocking allows us to do. There are many variants on port knocking and many programs that implement it. The following tutorial will use knockd as port-knocking server.
Download and install the knock-server rpm package:
$ wget http://li.nux.ro/download/nux/misc/el6/i386/knock-server-0.5-7.el6.nux.i686.rpm
The configuration file can be found under /etc/knockd.conf.
In the above configuration, we’ve stated that any host that sends a TCP SYN message to port 6000, then 7000 and finally to 8000, within 15 seconds, will cause the iptables command to be run. As you can see, the use of iptables is not hard-coded to knockd at all, meaning that any command can be run when the port sequence is triggered, allowing us to do all sorts of fancy stuff. To close it up, we do the same sequence in reverse order (that’s because we have configured it to do so).