Skip to content

Commit

Permalink
feat(maxconnection): notify client as same as openssh does
Browse files Browse the repository at this point in the history
  • Loading branch information
hugefiver committed Jul 15, 2024
1 parent 3875494 commit 8e7ae45
Showing 1 changed file with 18 additions and 5 deletions.
23 changes: 18 additions & 5 deletions ssh.go
Original file line number Diff line number Diff line change
Expand Up @@ -132,9 +132,11 @@ func StartSSHServer(config *ssh.ServerConfig, opt *Option) {
}

if !checkMaxConnections(connections.Add(1), maxConn, hardMaxConn, lossRatio) {
_ = conn.Close()
connections.Add(-1)
log.Infof("[Disconnect] reached max connections limit, disconnect from: %s", conn.RemoteAddr().String())
go func() {
disconnectWithMaxConenctions(conn)
connections.Add(-1)
log.Infof("[Disconnect] reached max connections limit, disconnect from: %s", conn.RemoteAddr().String())
}()
continue
}

Expand All @@ -153,8 +155,10 @@ func StartSSHServer(config *ssh.ServerConfig, opt *Option) {
pass := limiter.Allow(conn.RemoteAddr().String()).OK()
if !pass {
log.Infof("[Disconnect] out of rate limit, ip: %s", ip)
_ = conn.Close()
connections.Add(-1)
go func() {
disconnectWithMaxConenctions(conn)
connections.Add(-1)
}()
continue
}

Expand Down Expand Up @@ -189,6 +193,7 @@ func handleConn(sshCtx *SSHConnectionContext, config *ssh.ServerConfig) {
sshCtx.Connections.Add(-1)
defer sshCtx.SuccConnections.Add(-1)
if !ok {
disconnectWithMaxConenctions(sshCtx.Conn)
log.Infof("[Disconnect] reached max success connections, disconnect from %s", sshCtx.RemoteAddr().String())
return
}
Expand Down Expand Up @@ -260,3 +265,11 @@ func checkMaxConnections(curr, max, hardMax int64, ratio float64) bool {

return rand.Float64() >= (ratio + increaseRatio)
}

func disconnectWithMaxConenctions(conn net.Conn) {
// notify client just like openssh does
// see `drop_connection` of [`openssh/sshd.c`](https://github.com/openssh/openssh-portable/blob/master/sshd.c)
const msg = "Not allowed at this time\r\n"
_, _ = conn.Write([]byte(msg))
_ = conn.Close()
}

0 comments on commit 8e7ae45

Please sign in to comment.