ssh_exchange_identification: Connection closed by remote host 可能的问题

今天 ssh 登陆一台服务器的时候报错:

$ ssh vpsee@172.16.38.200
ssh_exchange_identification: Connection closed by remote host

单看这个错误信息没有啥用,因为可能有多种情况都会导致这一信息,多数时候用 ssh -vvvvv 也 debug 不到啥有用的东西出来。一般来说有这么几种情况和解决办法:

1、检查 /etc/hosts.deny 和 /etc/hosts.allow 里面是否屏蔽了某些帐户;
2、删除 ~/.ssh/known_hosts 里面的相关服务器条目试一下;
3、Debian 上 /var/run/sshd/ 的所属问题导致 SSH 不能启动
4、在某些发行版上升级 glibc 或 openssl 等软件包以后需要重启一下 sshd;
5、由于 ssh 试探或者 ssh 连结数太多,/etc/ssh/sshd_config 里面的 MaxStartups 默认参数配置不够用;
6、欢迎补充 …

这里遇到的就是“情况5”,控制台直接登陆服务器后检查 /var/log/secure 发现大量未经授权和失败的连接,典型的 ssh brute force 试探导致。先看一下帮助文件,看看 MaxStartups 10:30:60 是啥意思:

# man sshd_config
...
     MaxStartups
             ...
         Alternatively, random early drop can be enabled by specifying the
         three colon separated values “start:rate:full” (e.g. "10:30:60").
         sshd(8) will refuse connection attempts with a probability of
         “rate/100” (30%) if there are currently “start” (10) unauthenti-
         cated connections.  The probability increases linearly and all con-
         nection attempts are refused if the number of unauthenticated con-
         nections reaches “full” (60).
...

MaxStartups 默认设置是 10:30:60,意思是从第10个连接开始以30%的概率(递增)拒绝新连接,直到连接数达到60为止,可能因为 ssh ddos/brute force 触发了这个 MaxStartups 设置。根据当前 ssh 连接用户和服务器情况解决办法是,把这个值加大、在 /etc/hosts.allow 里只加上授权用户、或者使用 DenyHosts, Fail2ban 等工具屏蔽掉攻击源。