Score:17

How can I protect SSH?

id flag
Ali

I check /var/log/secure and I have these logs:

Jul  9 13:02:56 localhost sshd[30624]: Invalid user admin from 223.196.172.1 port 37566
Jul  9 13:02:57 localhost sshd[30624]: Connection closed by invalid user admin 223.196.172.1    port 37566 [preauth]
Jul  9 13:03:05 localhost sshd[30626]: Invalid user admin from 223.196.174.150 port 61445
Jul  9 13:03:05 localhost sshd[30626]: Connection closed by invalid user admin 223.196.174.150 port 61445 [preauth]
Jul  9 13:03:16 localhost sshd[30628]: Invalid user admin from 223.196.169.37 port 62329
Jul  9 13:03:24 localhost sshd[30628]: Connection closed by invalid user admin 223.196.169.37 port 62329 [preauth]
Jul  9 13:03:29 localhost sshd[30630]: Invalid user admin from 223.196.169.37 port 64099
Jul  9 13:03:30 localhost sshd[30630]: Connection closed by invalid user admin 223.196.169.37 port 64099 [preauth]
Jul  9 13:03:45 localhost sshd[30632]: Invalid user admin from 223.196.174.150 port 22816
Jul  9 13:03:46 localhost sshd[30632]: Connection closed by invalid user admin 223.196.174.150 port 22816 [preauth]
Jul  9 13:06:17 localhost sshd[30637]: Invalid user admin from 223.196.168.33 port 33176
Jul  9 13:06:17 localhost sshd[30637]: Connection closed by invalid user admin 223.196.168.33 port 33176 [preauth]
Jul  9 13:07:09 localhost sshd[30639]: Invalid user admin from 223.196.173.152 port 61780
Jul  9 13:07:25 localhost sshd[30641]: Invalid user admin from 223.196.168.33 port 54200
Jul  9 13:07:26 localhost sshd[30641]: Connection closed by invalid user admin 223.196.168.33 port 54200 [preauth]
...

It seems someone tries to log in by SSH. I disable login by root user and enable public/private key login, but is this a DDoS attack? And does it use RAM/CPU?

What should I do?

marcelm avatar
ng flag
_"I [...] enable public/private key login, ..."_ - But did you also disable password logins?
marcelm avatar
ng flag
[This answer](https://unix.stackexchange.com/a/503346/109651) may also be of interest.
Score:45
br flag

That's just the normal Internet background noise of people scanning for vulnerable servers.

You can add an iptables rule to rate limit incoming connections (e.g. four in four minutes) for a simple fix (but that will also lock you out if you open too many connections or someone forges SYN packets originating from your address):

iptables -A INPUT -p tcp -m tcp --dport 22 -m state --state NEW -m recent --update --seconds 240 --hitcount 4 --name ssh-v4 --mask 255.255.255.255 --rsource -j REJECT --reject-with tcp-reset
iptables -A INPUT -p tcp -m tcp --dport 22 -m state --state NEW -m recent --set --name ssh-v4 --mask 255.255.255.255 --rsource -j ACCEPT

The proper solution is to use a tool like fail2ban that parses the log file for failed logins and creates firewall rules on demand -- a bit more work to set up, but it requires an established connection and a failed authentication to trigger, so it will not react to forged connection attempts or successful logins like the simple approach does.

cn flag
how about changing the ssh port?
Michael Hampton avatar
cz flag
@njzk2 It only inconveniences yourself. The bots will find your alternate ssh port sooner or later.
us flag
More work to set up? On Debian `apt-get install fail2ban` will get you protection with reasonable defaults
LinuxSecurityFreak avatar
ru flag
@MichaelHampton There are 65535 ports, I somehow doubt the bots would take upon such range, but I may be mistaken. Do you know this for a fact?
br flag
@LinuxSecurityFreak, there is [shodan](https://shodan.io).
Michael Hampton avatar
cz flag
@LinuxSecurityFreak I don't change the ssh port personally, but I've heard numerous complaints from people over the years who did and _still_ got bots trying ssh on the new port they chose, even when it was not something obvious like 2222. And of course shodan scans everything. You can be sure they aren't the only ones.
au flag
@MichaelHampton Changing the port will get rid of *some* bots. Also, in what way is it inconvenient (beyond the initial setup)?
cn flag
@jonbentley having to remember to change it in every client you want to use to connect. Security by Obscurity is no security at all, you can rent a couple of AWS machines for less than $50 that will scan the entire IPv4 address space in a couple of hours. Better to just block the offenders than try and hide from them
au flag
@hardillb "having to remember" - that seems very use-case specific. I would think most people are not switching to new clients too frequently (or if they are the provisioning is probably within their control), and can simply store the settings once and then forget about it (using e.g. Ansible or Stow if you provision new machines frequently). "Security by obsurity is no security" is a common misconception. *By itself* it is no security, but it is a valid part of defence in depth and can give some mild benefits when used correctly.
Jason avatar
cn flag
@LinuxSecurityFreak re: "There are 65535 ports, I somehow doubt the bots would take upon such range" - I doubted it too, until I saw a client that had moved the port to something like 20502. It was published on shodan.io as an open port and the service was correctly identified. Impressive. And sobering.
de flag
I had an infrastructure operator recommend to me that I change sshd ports long ago, and I thought it was complete garbage, like just many of the comments, here, but I did it anyway. And we still get junk. But compared to the servers where we _havent_ changed, the ports, they're practically idle. It's been 15 years and no amount of Shodan-fu has pointed a large number of bots at our servers. YMMV. This is *not* security by obscurity. It's merely obscurity. The security comes from using strong ssh keys for authentication and not passwords. Also +1 for fail2ban :)
se flag
@LinuxSecurityFreak Look at the question. That bot was trying on different ports. Not port 22. So for the OP he's already facing a bot that is specifically scanning ports and not trying to ssh on port 22
tf flag
I'd not go for the blind rate-limit shown, this makes it far to easy to be DoS-ed out of your server, even by random scanning.
John Mee avatar
il flag
Actual personal experience here: changing the port number whilst not a real solution definitely works to lower the risk... at least on minor hosts. Combined with Key authentication was least effort to reward ratio - two lines changed and a nervous restart.
br flag
@Pelle, the rate limit is per source IP, so it's "only" vulnerable to targeted denial of service.
mx flag
@hardillb Yes, it’s just obscurity, but obscurity is often enough to deter a nontrivial percentage of attacks here. Unless you’re actively being targeted, most bots are not going to try any alternate ports at all (speaking from more than a decade of experience here), so simply changing the port, even if it’s a change to an ‘obvious’ alternate port, is enough to cut down significantly on the number of attackers that are actually a threat.
user avatar
sa flag
@slebetman That's the client port, it has nothing to do with the server port since if it was checking on different ports for the server, it wouldn't show up in the SSH logs.
tf flag
@SimonRichter: In that case, carry on :-)
in flag
Another bit of personal experience: fail2ban achieves next to nothing in practice here. All of the SSH scanning I get is from botnets, where each remote host only attempts 1 or 2 logins, which isn't enough to trigger fail2ban (you can see this in OP's log, as well). Disable password login and only use public key auth.
Score:9
in flag

As @Simon Richter mentionned, that's just internet background noise and you shouldn't worry. A few things you have to make sure are that:

Changing the port will make the problem go away, but it's security through obscurity and it can create the illusion of safety while providing none.

Here are a few other recommendations surrounding SSH, as well as counter arguments to mainstream "best practices" arguments.

Score:3
in flag

Are you in India? All those IP addresses listed are in the block:

223.196.160.0 - 223.196.191.255   

which according to the WHOIS database is allocated to

descr:   Andhra Pradesh State FiberNet Limited
address: 10-2-1,III Floor, FDC Complex,AC Guards,Hyderabad,Andhra Pradesh-500028

One short-term solution is to block the whole block 223.196.160.0/19 at the firewall, but that is micromanaging IP addresses and becomes an uphill battle.


Instead you could deny ALL ssh except for the source IPs that you know are trusted. Simply take care to not lock yourself out of your own host. If you don't have a static IP, you can permit a block, or possibly look at running a VPN server on the host.

Or if you don't need to permit SSH connections from the internet, just deny them and only reenable when its required.

user10489 avatar
nc flag
Or use port knocking to whitelist yourself when your IP changes.
Score:1
de flag
  1. Use only key-based auth. Many bots only attack password-based systems. Using password-based auth is bad idea anyway.
  2. Use https://www.sshguard.net/ : it blocks IPs after a couple of failed logins.
  3. Use random port (not 22), it will stop some bots.
  4. Make sure your system doesn't permit root login
  5. If you only login from your home, consider only open SSH for your IP/ISP or country.
Score:1
in flag

Here is a simple script I wrote to block all unauthorized attempts at logging into my dev server.

#!/bin/bash

ban=$HOME/banned.txt
b_log=/var/log/banned.log

log () {
cat $ban | uniq >>  $b_log
}

l_log () {
lastb | awk '{ print $3 }' | sed -r '/(Mon|Tue|Wed|Thu|Fri|Sat|Sun|boot|tty2)/d' | sort | sed '/^$/d' | uniq | tee $ban
}

drop () {
for x in $(cat $ban); do iptables -A INPUT -s $x -j DROP; done
}

l_log
drop
log
rm -f $ban
echo > /var/log/btmp
iptables-save

If you set the script to run via cron every minute, it will dramatically reduce the noise in your logs and block offending IPs giving them just 1 minute to attempt their brute force before being blocked.

It would be a good idea to insert your IP and any other IPs you access your server with to your firewall iptables -I INPUT -s xxx.xx.xxx.xx -j ACCEPT

A log of all IPs banned will be generated.

Criggie avatar
in flag
So you're taking the output logs of fail2ban, and permanently dropping those source IPs using iptables rules? Why not just tweak iptables to leave the bad addresses blocked for longer? You're also at risk of blocking your local IPs if you mis-key a password or similar, whereas fail2ban has "don't ever block these ranges" options.
HatLess avatar
in flag
No. I do not use fail2ban, just iptables. I am getting my input from `lastb`, the last failed log ins, then extracting just the IPs and dropping them.
iBug avatar
um flag
Sounds like you're reinventing fail2ban. F2B is already a comprehensive tool for exactly this task, no reason to refuse it.
Score:1
ck flag

1. Change your sshd listening port

As simple as it sounds, changing your port from the default 22 to a custom value (e.g. 2200) on a public IP could reduce the number of port scans from thousands a day to a few dozen. For a tutorial see here.

That being said, while this does reduce the annoyance of being port-scanned, it DOES NOT provide real security. "Security by obscurity" is a myth and nothing more.

2. Use public key login and disable password login

Bots might guess a password right, but they're never going to guess a private key right. As long as you use modern algorithms and don't leak your key accidentally. For a tutorial see here.

Note that this does mean you will no longer be able to login from any random machine, unless you carry the key with you (which you need to secure via some other way).

3. Use fail2ban

If they fail 5 times, ban them from trying again for a day or something. That'll show them. Very effective against brute force attempts. For a tutorial see here.

The downside is that you might lock yourself out if you've got wobbly fingers one day (drunk or something, I don't know).

4. Pre-ban a list of IPs known for abusive use

Sources like AbuseIPDB maintain big lists of known malicious IPs accessible via API. You will need an API key to use it, but you can register a free account easily enough. Pull the list and use something like iptables to ban those known IPs in bulk. Set up a cron job to automate it periodically for best effect. Here's a very simple script I wrote (and am personally using) to do just that. Feel free to use it as reference, but DON'T USE IT IN PRODUCTION.

In my personal experience, this method is equally effective (if not more so) as method #3.


Personally, I use all 4 methods listed above, and my VPS might get one or two malicious login attempts in my security log at most, in a bad month. Here's the interception history of iptables via method #4:

$ abip-hist
Chain abip-ban (1 references)
 pkts bytes target     prot opt in     out     source               destination
  362 14480 DROP       all  --  *      *       45.143.200.6         0.0.0.0/0
  307 12280 DROP       all  --  *      *       185.156.73.104       0.0.0.0/0
  288 12672 DROP       all  --  *      *       212.133.164.75       0.0.0.0/0
  277 19911 DROP       all  --  *      *       146.88.240.4         0.0.0.0/0
  250 11000 DROP       all  --  *      *       212.133.164.14       0.0.0.0/0
  230  9200 DROP       all  --  *      *       45.146.164.213       0.0.0.0/0
  215  8600 DROP       all  --  *      *       185.156.73.67        0.0.0.0/0
  214  8560 DROP       all  --  *      *       5.188.206.18         0.0.0.0/0
  202  8080 DROP       all  --  *      *       193.27.228.63        0.0.0.0/0
  201  8040 DROP       all  --  *      *       193.27.228.64        0.0.0.0/0
  199  7960 DROP       all  --  *      *       193.27.228.59        0.0.0.0/0
  197  7880 DROP       all  --  *      *       193.27.228.65        0.0.0.0/0
  197  7880 DROP       all  --  *      *       193.27.228.61        0.0.0.0/0
  196  7840 DROP       all  --  *      *       45.135.232.119       0.0.0.0/0
  196  7840 DROP       all  --  *      *       193.27.228.60        0.0.0.0/0
  196  7840 DROP       all  --  *      *       193.27.228.58        0.0.0.0/0
  189  7560 DROP       all  --  *      *       45.146.165.149       0.0.0.0/0
  184  7360 DROP       all  --  *      *       45.155.205.247       0.0.0.0/0
  184  7360 DROP       all  --  *      *       195.54.160.228       0.0.0.0/0
  182  7280 DROP       all  --  *      *       45.143.203.12        0.0.0.0/0
  181  7240 DROP       all  --  *      *       45.141.84.57         0.0.0.0/0
  180  7200 DROP       all  --  *      *       45.135.232.85        0.0.0.0/0
  176  7040 DROP       all  --  *      *       45.146.165.148       0.0.0.0/0
...
this goes on for 1700 lines...

$ uptime
06:36:49 up 16 days, 15:24
Z4-tier avatar
us flag
+1 for "change your port". Just don't change it to something equally as attractive (or more) to a would-be attacker. Use an obscure, unassigned, higher-numbered port; something above 10000. I used to run ssh on 23 (the telnet port) just for *ha-ha's* and wow did that get a lot of connections.
Score:0
er flag
lev

As other answers mentioned, you don't need to worry to much about it, but if you do want to add another layer of security, you can try using port knocking.

The idea is to keep the ssh port closed, and only open it to ips, that perform a specific sequence of operation prior, something like:

syn port 1000
syn port 2000
syn port 3000
# ssh port is now open
ssh ...

can get more details here: https://www.rapid7.com/blog/post/2017/10/04/how-to-secure-ssh-server-using-port-knocking-on-ubuntu-linux/

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.