优化SSH默认单次协商并记录重载回连阻塞

This commit is contained in:
xuans committed 2026-09-30 19:09:52 +08:00
1 parent 189b79849d
commit 1a317c2175
5 files changed
+161 -3

No files matched your search

+12 -3
View File
@@ -85,7 +85,7 @@ func (f SSHFactory) connect(ctx context.Context, server Server, requireSFTP bool
}
timeoutContext, cancel := context.WithTimeout(ctx, timeout)
defer cancel()
sshClient, err := connectSSHClient(timeoutContext, server, authMethods, algorithms)
sshClient, err := connectSSHClient(timeoutContext, server, authMethods, algorithms, len(f.HostKeyAlgorithms) == 0)
if err != nil {
return nil, err
}
@@ -145,10 +145,19 @@ func connectSSHClient(
server Server,
authMethods []ssh.AuthMethod,
algorithms []string,
preferSingleNegotiation bool,
) (*ssh.Client, error) {
address := net.JoinHostPort(server.Address, fmt.Sprintf("%d", server.Port))
var mismatchErrors []string
algorithmGroups := make([][]string, 0, len(algorithms)+1)
if preferSingleNegotiation {
algorithmGroups = append(algorithmGroups, algorithms)
}
for _, algorithm := range algorithms {
algorithmGroups = append(algorithmGroups, []string{algorithm})
}
for _, algorithmGroup := range algorithmGroups {
algorithm := strings.Join(algorithmGroup, ",")
if err := ctx.Err(); err != nil {
return nil, fmt.Errorf("连接 SSH 服务器超时:%w", err)
}
@@ -167,7 +176,7 @@ func connectSSHClient(
config := &ssh.ClientConfig{
User: server.Username,
Auth: authMethods,
HostKeyAlgorithms: []string{algorithm},
HostKeyAlgorithms: algorithmGroup,
HostKeyCallback: func(_ string, _ net.Addr, key ssh.PublicKey) error {
fingerprint := ssh.FingerprintSHA256(key)
if fingerprint != server.HostKeyFingerprint {
@@ -201,7 +210,7 @@ func connectSSHClient(
continue
}
var negotiationError *ssh.AlgorithmNegotiationError
if errors.As(handshakeErr, &negotiationError) && negotiationError.What == "host key" {
if len(algorithmGroup) == 1 && errors.As(handshakeErr, &negotiationError) && negotiationError.What == "host key" {
continue
}
return nil, fmt.Errorf("SSH 握手失败:%w", handshakeErr)
@@ -0,0 +1,98 @@
package deployment
import (
"context"
"errors"
"sync/atomic"
"testing"
"time"
"golang.org/x/crypto/ssh"
)
func TestSSHFactoryDefaultNegotiatesOnce(t *testing.T) {
for _, reject := range []bool{false, true} {
name := "accepted"
if reject {
name = "rejected"
}
t.Run(name, func(t *testing.T) {
_, privateKey := newTestSSHSigner(t)
hostSigner, _ := newTestSSHSigner(t)
server := startTestSSHServer(t, func(ssh.PublicKey) error {
if reject {
return errors.ErrUnsupported
}
return nil
}, hostSigner)
factory := SSHFactory{
Secrets: staticSecretReader{"secret://test": {"private_key": privateKey}},
Timeout: 2 * time.Second,
}
client, err := factory.ConnectShell(t.Context(), testSSHServerModel(
server, "secret://test", ssh.FingerprintSHA256(hostSigner.PublicKey()),
))
if client != nil {
defer client.Close()
}
if (err != nil) != reject {
t.Fatalf("reject=%t err=%v", reject, err)
}
if got := server.accepted.Load(); got != 1 {
t.Fatalf("connections=%d; want=1", got)
}
})
}
}
func TestSSHSingleNegotiationFallsBackToRegisteredFingerprint(t *testing.T) {
clientSigner, _ := newTestSSHSigner(t)
ecdsaHostSigner := newTestECDSAHostSigner(t)
ed25519HostSigner, _ := newTestSSHSigner(t)
var authenticated atomic.Int32
server := startTestSSHServer(t, func(ssh.PublicKey) error {
authenticated.Add(1)
return nil
}, ecdsaHostSigner, ed25519HostSigner)
ctx, cancel := context.WithTimeout(t.Context(), 2*time.Second)
defer cancel()
client, err := connectSSHClient(ctx,
testSSHServerModel(server, "secret://test", ssh.FingerprintSHA256(ed25519HostSigner.PublicKey())),
[]ssh.AuthMethod{ssh.PublicKeys(clientSigner)},
[]string{ssh.KeyAlgoECDSA256, ssh.KeyAlgoED25519}, true,
)
if err != nil {
t.Fatal(err)
}
defer client.Close()
if got := server.accepted.Load(); got != 3 {
t.Fatalf("connections=%d; want=3", got)
}
if got := authenticated.Load(); got != 1 {
t.Fatalf("authenticated=%d; want=1", got)
}
}
func TestSSHFactoryDefaultRejectsUnknownFingerprintBeforeAuthentication(t *testing.T) {
_, privateKey := newTestSSHSigner(t)
hostSigner, _ := newTestSSHSigner(t)
var authenticated atomic.Int32
server := startTestSSHServer(t, func(ssh.PublicKey) error {
authenticated.Add(1)
return nil
}, hostSigner)
factory := SSHFactory{
Secrets: staticSecretReader{"secret://test": {"private_key": privateKey}},
Timeout: 2 * time.Second,
}
client, err := factory.ConnectShell(t.Context(), testSSHServerModel(server, "secret://test", "SHA256:unregistered"))
if client != nil {
defer client.Close()
}
if err == nil {
t.Fatal(err)
}
if got := authenticated.Load(); got != 0 {
t.Fatalf("authenticated=%d; want=0", got)
}
}