Blog·Tanky WooABOUTTAGSRSS

最近发现个别服务器 ssh 登录时偶尔出现失败,发现和 MaxStartups 有关。

本地模拟环境:

  • 10.0.7.113: 客户端
  • 10.0.7.9: 服务端

客户端 ssh 连接时收到的报错信息:

kex_exchange_identification: Connection closed by remote host
Connection closed by 10.0.7.9 port 22

抓包看已经到应用层 ssh 协商阶段,但是服务端在收到客户端的 ssh 协议版本包之前,就已经主动关闭连接,发送了 FIN + ACK

(客户端抓包)

(服务端抓包)

在服务端 /etc/ssh/sshd_config 将日志级别调整到 LogLevel VERBOSE,可以看到日志:

2020-09-02T12:48:48.289609+08:00 gentoo-pc sshd[3480]: drop connection #3 from [10.0.7.113]:57645 on [10.0.7.9]:22 past MaxStartups

日志层面显示客户端端口 57645 对应上面的异常连接数据包。另外提到了 past MaxStartups,查阅 man 手册:

MaxStartups
    Specifies the maximum number of concurrent unauthenticated connections to the SSH daemon.
    Additional connections will be dropped until authentication succeeds or the LoginGraceTime expires for a connection.
    The default is 10:30:100.

    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) unauthenticated connections.
    The probability increases linearly and all connection attempts are refused if the number of unauthenticated connections reaches full (60).

即控制并发初始化连接的个数,初始化连接即还未到认证层面的连接,如默认的 10:30:100,表示如果超过 10 个并发初始化连接,则后续的连接由 30% 的几率直接被关闭,如果超过 100 个连接,则所有新的连接 100% 直接关闭。

再比如我本地模拟测试,配置 MaxStartups 3:100:3,即表示并发初始化连接超过 3 个时,直接 100% 丢包,所以我开 tmux 四个窗口同时登陆服务端,总会有一个连接报错并关闭连接。

结合实际的场景为何会出现这个问题,我们的服务器都做了 ssh 白名单防火墙限制,只有白名单的网段可以登录,其余数据包在防火墙层面直接丢弃;但是个别服务器因为一些原因,未开启此配置,导致有大量的 ssh 端口扫描,自然就达到了 MaxStartups 的限制,也就出现了偶尔丢包的情况。