A Cure for the Common SSH Login Attack

-by Jon Scully

Introduction

A few months ago, I began seeing our 'secure' log files fill up with entries stating: "Failed password for illegal user [username]". I decided to search the Internet to find out if others were experiencing these attacks and, hopefully, find a solution. I did uncover a lot of information on the subject, but discovered only a few script-based solutions. None of these, however, seemed... well... elegant.

What I wanted was a way to stop the attacks altogether, yet allow ssh access from anywhere, when needed. In addition, I wanted to avoid using an approach that was so complicated it could lead to more pain than I was experiencing from the original problem.

My requirements looked something like this:

Keep port 22 closed, until needed

Provide a simple way to open and close port 22 from any remote location

Ensure the method used is reasonably difficult for attackers to discover

Use an "elegant" method (i.e. not a lot of software)

The solution should behave similar to the following shell prompt activity:

Note that the ports used to open and close port 22 should appear closed, as well. This approach would be a sort of simplified "port knocking" technique.

Proposed Solution

The 'recent' module in iptables is designed to detect malicious access attempts and then help block or at least honeypot the potential intruder with delays. I've sort of turned this module on its head and, instead, used it to let people in.

The following represents the contents of an iptables file, drawn from a Red Hat distribution (the usual path is /etc/sysconfig/iptables). The highlighted text outlines the changes needed to support our style of port knocking.

Note that there is a "close" port on either side of the "open" port. This should cause most linear port scans (ascending or descending) to leave port 22 closed, upon completion.

For an even more robust approach, use two separate "open" ports -- such as a knock at port 1300, followed by a knock at port 1600. Also keep in mind, once you have ssh-connected, you can then close the port without losing your established connection.

Conclusion

What's really convenient about this method is, when you're at a trusted location (say, in the office) and you unlock a target site (say, a home server), you need only knock once; The port will stay open for that specific source IP address, indefinitely (until you deliberately close the port or iptables is restarted). If you attempt to use the port from another location (say, a client's office), it will appear closed -- until you knock.

What I find most elegant about this approach is that you don't have to fill up your iptables with dozens of DROP entries in order to block the world of would-be attackers.