8 Ways to Defend Against Brute Force SSH Attacks

|

I looked at my server’s auth logs today and was unsettled to find thousands of lines like these:

Feb 12 06:49:52 localhost sshd[25416]: Invalid user photo from xxx.xxx.xxx.xxx
Feb 12 06:49:52 localhost sshd[25416]: pam_unix(sshd:auth): check pass; user unknown
Feb 12 06:49:52 localhost sshd[25416]: pam_unix(sshd:auth): authentication failure; logname= uid=0 euid=0 tty=ssh ruser= rhost=some.random.domain
Feb 12 06:49:54 localhost sshd[25416]: Failed password for invalid user photo from xxx.xxx.xxx.xxx port 49608 ssh2

I was looking at someone running a brute force attack on my server trying to gain SSH access. Looking further back in the logs, I found crackers (not the derogatory term for white people but people who break security maliciously) had been attacking me for at least a month. Luckily the unsophisticated attack simply tried various username/password combinations. After common usernames like root, admin, and user were tried, the attackers used names like aaron, gary, stephanie, etc.

Alright, time to shut these guys down. (All setting changes were made in /etc/ssh/sshd_config and on Ubuntu unless otherwise specified.)

1. Don’t Permit Root Login

PermitRootLogin no

2. Specify Which Accounts Can Use SSH

AllowUsers [user1] [user2]

3. Only Allow Public Key Authentication

I’d already generated an RSA key with ssh-keygen -t rsa on my personal computer. This created the files /home/username/.ssh/id_rsa (the private key) and /home/username/.ssh/id_rsa.pub (the public key). I checked that my server had the public key in its /home/username/authorized_keys.

Now I just needed to disable password authentication by specifying PasswordAuthentication no and restarting the sshd daemon: /etc/init.d/sshd restart.

4. Use iptables to Throttle Repeated Connections

Following this helpful post, I made the following changes to my iptables as root.

Mitigating against SSH brute force attacks using Netfilter and the recent modulelink
1
2
3
4
5
iptables -A INPUT -p tcp --dport 22 -m state --state NEW -m recent --set --name SSH
iptables -N SSH_WHITELIST
iptables -A INPUT -p tcp --dport 22 -m state --state NEW -j SSH_WHITELIST
iptables -A INPUT -p tcp --dport 22 -m state --state NEW -m recent --update --seconds 60 --hitcount 4 --rttl --name SSH -j ULOG --ulog-prefix SSH_brute_force
iptables -A INPUT -p tcp --dport 22 -m state --state NEW -m recent --update --seconds 60 --hitcount 4 --rttl --name SSH -j DROP

According to the author Andrew,

This will allow three port 22 connections from any given IP address within a 60 second period, and require 60 seconds of no subsequent connection attempts before it will resume allowing connections again. The –rttl option also takes into account the TTL of the datagram when matching packets, so as to endeavor to mitigate against spoofed source addresses…[The ruleset] has the (arguably) added benefit of not hosing any established SSH connections from the host that has made too many SSH connections in a short period of time, and allows for whitelisting.

And install iptables-persistent to retain these rules after reboot. For a different set of iptable rules, see this post.

5. Automatically Blacklist IP Addresses With DenyHosts

DenyHosts is a handy script that thwarts attacks by scanning your auth log and automatically adding IP addresses to /etc/hosts.deny.

sudo apt-get install denyhosts

6. Change SSH Port Number

Instead of using standard port 22, use a non-standard port to avoid port scans. Check which ports are open and have TCP connections:

netstat -vatn

Port numbers are divided into three ranges: well-known ports (0–1023), registered ports (1024–49151), and dynamic or private ports (49152–65535). Choose one from the third range to not conflict with existing protocols. Then restart ssh:

/etc/init.d/ssh restart

Log messages like the one below without a subsequent success or error message means someone’s port scanning your machine.

localhost sshd[14453]: Connection from xxx.xxx.xxx.xxx port xxxxx
localhost sshd[14453]: Did not receive identification string from xxx.xxx.xxx.xxx

7. Log More Info

I wanted keep a closer eye on my auth logs so I set

LogLevel VERBOSE

8. Display an SSH Banner

I uncommented Banner /etc/issue.net to display a custom message to people who try to login. This doesn’t add any security and is just for fun. People who are determined to break into my box won’t give a shit about a no trespassing sign. I just wanted to give the bad guys a chuckle. I could’ve put up something like this:

Mitigating against SSH brute force attacks using Netfilter and the recent modulelink
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
***************************************************************************
                            NOTICE TO USERS


This computer system is the private property of its owner, whether
individual, corporate or government.  It is for authorized use only.
Users (authorized or unauthorized) have no explicit or implicit
expectation of privacy.

Any or all uses of this system and all files on this system may be
intercepted, monitored, recorded, copied, audited, inspected, and
disclosed to your employer, to authorized site, government, and law
enforcement personnel, as well as authorized officials of government
agencies, both domestic and foreign.

By using this system, the user consents to such interception, monitoring,
recording, copying, auditing, inspection, and disclosure at the
discretion of such personnel or officials.  Unauthorized or improper use
of this system may result in civil and criminal penalties and
administrative or disciplinary action, as appropriate. By continuing to
use this system you indicate your awareness of and consent to these terms
and conditions of use. LOG OFF IMMEDIATELY if you do not agree to the
conditions stated in this warning.

****************************************************************************

But I opted for this:

Mitigating against SSH brute force attacks using Netfilter and the recent modulelink
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
                         ..-:"''         ''"-..
                      .-'                      '-.
                    .'              .     .       '.
                  .'   .          .    .      .    .''.
                .'  .    .       .   .   .     .   . ..:.
              .' .   . .  .       .   .   ..  .   . ....::.
             ..   .   .      .  .    .     .  ..  . ....:IA.
            .:  .   .    .    .  .  .    .. .  .. .. ....:IA.
           .: .   .   ..   .    .     . . .. . ... ....:.:VHA.
           '..  .  .. .   .       .  . .. . .. . .....:.::IHHB.
          .:. .  . .  . .   .  .  . . . ...:.:... .......:HIHMM.
         .:.... .   . ."::"'.. .   .  . .:.:.:II;,. .. ..:IHIMMA
         ':.:..  ..::IHHHHHI::. . .  ...:.::::.,,,. . ....VIMMHM
        .:::I. .AHHHHHHHHHHAI::. .:...,:IIHHHHHHMMMHHL:. . VMMMM
       .:.:V.:IVHHHHHHHMHMHHH::..:" .:HIHHHHHHHHHHHHHMHHA. .VMMM.
       :..V.:IVHHHHHMMHHHHHHHB... . .:VPHHMHHHMMHHHHHHHHHAI.:VMMI
       ::V..:VIHHHHHHMMMHHHHHH. .   .I":IIMHHMMHHHHHHHHHHHAPI:WMM
       ::". .:.HHHHHHHHMMHHHHHI.  . .:..I:MHMMHHHHHHHHHMHV:':H:WM
       :: . :.::IIHHHHHHMMHHHHV  .ABA.:.:IMHMHMMMHMHHHHV:'. .IHWW
       '.  ..:..:.:IHHHHHMMHV" .AVMHMA.:.'VHMMMMHHHHHV:' .  :IHWV
        :.  .:...:".:.:TPP"   .AVMMHMMA.:. "VMMHHHP.:... .. :IVAI
       .:.   '... .:"'   .   ..HMMMHMMMA::. ."VHHI:::....  .:IHW'
       ...  .  . ..:IIPPIH: ..HMMMI.MMMV:I:.  .:ILLH:.. ...:I:IM
     : .   .'"' .:.V". .. .  :HMMM:IMMMI::I. ..:HHIIPPHI::'.P:HM.
     :.  .  .  .. ..:.. .    :AMMM IMMMM..:...:IV":T::I::.".:IHIMA
     'V:.. .. . .. .  .  .   'VMMV..VMMV :....:V:.:..:....::IHHHMH
       "IHH:.II:.. .:. .  . . . " :HB"" . . ..PI:.::.:::..:IHHMMV"
        :IP""HHII:.  .  .    . . .'V:. . . ..:IH:.:.::IHIHHMMMMM"
        :V:. VIMA:I..  .     .  . .. . .  .:.I:I:..:IHHHHMMHHMMM
        :"VI:.VWMA::. .:      .   .. .:. ..:.I::.:IVHHHMMMHMMMMI
        :."VIIHHMMA:.  .   .   .:  .:.. . .:.II:I:AMMMMMMHMMMMMI
        :..VIHIHMMMI...::.,:.,:!"I:!"I!"I!"V:AI:VAMMMMMMHMMMMMM'
        ':.:HIHIMHHA:"!!"I.:AXXXVVXXXXXXXA:."HPHIMMMMHHMHMMMMMV
          V:H:I:MA:W'I :AXXXIXII:IIIISSSSSSXXA.I.VMMMHMHMMMMMM
            'I::IVA ASSSSXSSSSBBSBMBSSSSSSBBMMMBS.VVMMHIMM'"'
             I:: VPAIMSSSSSSSSSBSSSMMBSSSBBMMMMXXI:MMHIMMI
            .I::. "H:XIIXBBMMMMMMMMMMMMMMMMMBXIXXMMPHIIMM'
            :::I.  ':XSSXXIIIIXSSBMBSSXXXIIIXXSMMAMI:.IMM
            :::I:.  .VSSSSSISISISSSBII:ISSSSBMMB:MI:..:MM
            ::.I:.  ':"SSSSSSSISISSXIIXSSSSBMMB:AHI:..MMM.
            ::.I:. . ..:"BBSSSSSSSSSSSSBBBMMMB:AHHI::.HMMI
            :..::.  . ..::":BBBBBSSBBBMMMB:MMMMHHII::IHHMI
            ':.I:... ....:IHHHHHMMMMMMMMMMMMMMMHHIIIIHMMV"
              "V:. ..:...:.IHHHMMMMMMMMMMMMMMMMHHHMHHMHP'
               ':. .:::.:.::III::IHHHHMMMMMHMHMMHHHHM"
                 "::....::.:::..:..::IIIIIHHHHMMMHHMV"
                   "::.::.. .. .  ...:::IIHHMMMMHMV"
                     "V::... . .I::IHHMMV"'
                       '"VHVHHHAHHHHMMV:"'

Hopefully this helps some people out there. For further reading check out: