生产部署整改阶段检查点
This commit is contained in:
1 parent
f3348cf95d
commit
92d4b3d398
56 files changed
+4178
-240
No files matched your search
@@ -39,6 +39,7 @@ type Server struct {
|
||||
PrivateKeyPath string `json:"private_key_path"`
|
||||
CertificateChainPath string `json:"certificate_chain_path"`
|
||||
WebServer WebServer `json:"web_server"`
|
||||
ValidationCommand []string `json:"validation_command,omitempty"`
|
||||
ReloadCommand []string `json:"reload_command,omitempty"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
@@ -70,6 +71,12 @@ func (s Server) Normalize() Server {
|
||||
if len(s.ReloadCommand) == 0 {
|
||||
s.ReloadCommand = DefaultReloadCommand(s.WebServer)
|
||||
}
|
||||
if len(s.ValidationCommand) == 0 {
|
||||
s.ValidationCommand = DefaultValidationCommand(s.WebServer)
|
||||
}
|
||||
for index := range s.ValidationCommand {
|
||||
s.ValidationCommand[index] = strings.TrimSpace(s.ValidationCommand[index])
|
||||
}
|
||||
for index := range s.ReloadCommand {
|
||||
s.ReloadCommand[index] = strings.TrimSpace(s.ReloadCommand[index])
|
||||
}
|
||||
@@ -172,17 +179,28 @@ func (s Server) Validate() error {
|
||||
if s.WebServer != WebServerNginx && s.WebServer != WebServerCaddy && s.WebServer != WebServerApache && s.WebServer != WebServerCustom {
|
||||
return fmt.Errorf("网站服务类型无效:%s", s.WebServer)
|
||||
}
|
||||
if len(s.ReloadCommand) == 0 || s.ReloadCommand[0] == "" {
|
||||
return errors.New("reload 命令不能为空")
|
||||
if err := validateServerCommand("配置校验", s.ValidationCommand); err != nil {
|
||||
return err
|
||||
}
|
||||
for _, argument := range s.ReloadCommand {
|
||||
if argument == "" || strings.ContainsAny(argument, "\x00\r\n") {
|
||||
return errors.New("reload 命令参数无效")
|
||||
}
|
||||
if err := validateServerCommand("reload", s.ReloadCommand); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func DefaultValidationCommand(webServer WebServer) []string {
|
||||
switch WebServer(strings.ToLower(strings.TrimSpace(string(webServer)))) {
|
||||
case WebServerNginx:
|
||||
return []string{"nginx", "-t"}
|
||||
case WebServerCaddy:
|
||||
return []string{"caddy", "validate", "--config", "/etc/caddy/Caddyfile"}
|
||||
case WebServerApache:
|
||||
return []string{"apachectl", "configtest"}
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
func DefaultReloadCommand(webServer WebServer) []string {
|
||||
switch WebServer(strings.ToLower(strings.TrimSpace(string(webServer)))) {
|
||||
case WebServerNginx:
|
||||
@@ -196,6 +214,18 @@ func DefaultReloadCommand(webServer WebServer) []string {
|
||||
}
|
||||
}
|
||||
|
||||
func validateServerCommand(label string, command []string) error {
|
||||
if len(command) == 0 || command[0] == "" {
|
||||
return fmt.Errorf("%s命令不能为空", label)
|
||||
}
|
||||
for _, argument := range command {
|
||||
if argument == "" || strings.ContainsAny(argument, "\x00\r\n") {
|
||||
return fmt.Errorf("%s命令参数无效", label)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func RemotePath(value string) string {
|
||||
value = strings.TrimSpace(value)
|
||||
if strings.ContainsAny(value, "\x00\r\n") {
|
||||
|
||||
@@ -10,6 +10,23 @@ func TestServerUsesDefaultReloadCommand(t *testing.T) {
|
||||
if len(server.ReloadCommand) != 3 || server.ReloadCommand[0] != "nginx" {
|
||||
t.Fatalf("Nginx 默认 reload 命令错误:%v", server.ReloadCommand)
|
||||
}
|
||||
if len(server.ValidationCommand) != 2 || server.ValidationCommand[0] != "nginx" || server.ValidationCommand[1] != "-t" {
|
||||
t.Fatalf("Nginx 默认配置校验命令错误:%v", server.ValidationCommand)
|
||||
}
|
||||
}
|
||||
|
||||
func TestServerRequiresCustomValidationCommand(t *testing.T) {
|
||||
server := testServer("one")
|
||||
server.WebServer = WebServerCustom
|
||||
server.ValidationCommand = nil
|
||||
server.ReloadCommand = []string{"service-control", "reload"}
|
||||
if err := server.Validate(); err == nil {
|
||||
t.Fatal("自定义网站服务未配置校验命令时应被拒绝")
|
||||
}
|
||||
server.ValidationCommand = []string{"service-control", "validate"}
|
||||
if err := server.Validate(); err != nil {
|
||||
t.Fatalf("自定义网站服务配置有效命令后应通过校验:%v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestServerUsesDefaultCertificatePathTemplates(t *testing.T) {
|
||||
@@ -108,4 +125,9 @@ func TestServerRejectsPasswordStyleOrUnsafeConfiguration(t *testing.T) {
|
||||
if err := server.Validate(); err == nil {
|
||||
t.Fatal("reload 参数包含换行时应拒绝服务器配置")
|
||||
}
|
||||
server = testServer("one")
|
||||
server.ValidationCommand = []string{"nginx", "-t\nrm"}
|
||||
if err := server.Validate(); err == nil {
|
||||
t.Fatal("配置校验参数包含换行时应拒绝服务器配置")
|
||||
}
|
||||
}
|
||||
@@ -196,6 +196,13 @@ func (s *Service) deployOne(ctx context.Context, server Server, artifact Artifac
|
||||
temporary = temporary[:len(temporary)-1]
|
||||
installed = append(installed, file.path)
|
||||
}
|
||||
validationResult, err := client.Run(ctx, server.ValidationCommand)
|
||||
if err != nil || validationResult.ExitCode != 0 {
|
||||
if err == nil {
|
||||
err = fmt.Errorf("退出码 %d", validationResult.ExitCode)
|
||||
}
|
||||
return failed(fmt.Sprintf("配置校验失败:%v", err))
|
||||
}
|
||||
commandResult, err := client.Run(ctx, server.ReloadCommand)
|
||||
if err != nil || commandResult.ExitCode != 0 {
|
||||
if err == nil {
|
||||
@@ -204,7 +211,7 @@ func (s *Service) deployOne(ctx context.Context, server Server, artifact Artifac
|
||||
return failed(fmt.Sprintf("reload 失败:%v", err))
|
||||
}
|
||||
result.Status = "success"
|
||||
result.Message = "证书部署并 reload 成功"
|
||||
result.Message = "证书部署、配置校验并 reload 成功"
|
||||
result.BackupID = backupID
|
||||
return result
|
||||
}
|
||||
|
||||
@@ -15,9 +15,10 @@ type memoryFile struct {
|
||||
|
||||
type memoryClient struct {
|
||||
files map[string]memoryFile
|
||||
command []string
|
||||
runResult CommandResult
|
||||
runErr error
|
||||
commands [][]string
|
||||
runResults []CommandResult
|
||||
runErrors []error
|
||||
runIndex int
|
||||
uploadError string
|
||||
removeError string
|
||||
renameError string
|
||||
@@ -25,7 +26,7 @@ type memoryClient struct {
|
||||
}
|
||||
|
||||
func newMemoryClient() *memoryClient {
|
||||
return &memoryClient{files: map[string]memoryFile{}, runResult: CommandResult{ExitCode: 0}}
|
||||
return &memoryClient{files: map[string]memoryFile{}}
|
||||
}
|
||||
|
||||
func (c *memoryClient) MkdirAll(context.Context, string) error { return nil }
|
||||
@@ -68,8 +69,18 @@ func (c *memoryClient) Remove(_ context.Context, path string) error {
|
||||
}
|
||||
|
||||
func (c *memoryClient) Run(_ context.Context, command []string) (CommandResult, error) {
|
||||
c.command = append([]string(nil), command...)
|
||||
return c.runResult, c.runErr
|
||||
c.commands = append(c.commands, append([]string(nil), command...))
|
||||
index := c.runIndex
|
||||
c.runIndex++
|
||||
var result CommandResult
|
||||
var err error
|
||||
if index < len(c.runResults) {
|
||||
result = c.runResults[index]
|
||||
}
|
||||
if index < len(c.runErrors) {
|
||||
err = c.runErrors[index]
|
||||
}
|
||||
return result, err
|
||||
}
|
||||
|
||||
func (c *memoryClient) Close() error { return nil }
|
||||
@@ -101,8 +112,8 @@ func TestDeployReplacesFilesAndKeepsBackup(t *testing.T) {
|
||||
if string(client.files[server.CertificatePath].data) != "new-cert" || client.files[server.PrivateKeyPath].mode != 0o600 {
|
||||
t.Fatalf("远程证书内容或权限错误:%+v", client.files)
|
||||
}
|
||||
if len(client.command) != 3 || client.command[0] != "nginx" {
|
||||
t.Fatalf("reload 命令错误:%v", client.command)
|
||||
if len(client.commands) != 2 || len(client.commands[0]) != 2 || client.commands[0][1] != "-t" || len(client.commands[1]) != 3 || client.commands[1][0] != "nginx" {
|
||||
t.Fatalf("配置校验或 reload 命令错误:%v", client.commands)
|
||||
}
|
||||
backupCount := 0
|
||||
for path := range client.files {
|
||||
@@ -117,7 +128,7 @@ func TestDeployReplacesFilesAndKeepsBackup(t *testing.T) {
|
||||
|
||||
func TestDeployRollsBackWhenReloadFails(t *testing.T) {
|
||||
client := newMemoryClient()
|
||||
client.runResult.ExitCode = 1
|
||||
client.runResults = []CommandResult{{ExitCode: 0}, {ExitCode: 1}}
|
||||
server := testServer("server-1")
|
||||
client.files[server.CertificatePath] = memoryFile{data: []byte("old-cert"), mode: 0o644}
|
||||
service := NewService(memoryFactory{clients: map[string]*memoryClient{server.ID: client}})
|
||||
@@ -138,9 +149,34 @@ func TestDeployRollsBackWhenReloadFails(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeployRollsBackWhenValidationFailsWithoutReload(t *testing.T) {
|
||||
client := newMemoryClient()
|
||||
client.runResults = []CommandResult{{ExitCode: 1}}
|
||||
server := testServer("server-1")
|
||||
client.files[server.CertificatePath] = memoryFile{data: []byte("old-cert"), mode: 0o644}
|
||||
client.files[server.CertificateChainPath] = memoryFile{data: []byte("old-chain"), mode: 0o644}
|
||||
client.files[server.PrivateKeyPath] = memoryFile{data: []byte("old-key"), mode: 0o600}
|
||||
service := NewService(memoryFactory{clients: map[string]*memoryClient{server.ID: client}})
|
||||
report := service.Deploy(context.Background(), []Target{{Server: server}}, testArtifact())
|
||||
if report.Status != "failed" || report.Failed != 1 || !strings.Contains(report.Results[0].Message, "配置校验失败") {
|
||||
t.Fatalf("配置校验失败结果错误:%+v", report)
|
||||
}
|
||||
if len(client.commands) != 1 || client.commands[0][1] != "-t" {
|
||||
t.Fatalf("配置校验失败后不应执行 reload:%v", client.commands)
|
||||
}
|
||||
if string(client.files[server.CertificatePath].data) != "old-cert" || string(client.files[server.CertificateChainPath].data) != "old-chain" || string(client.files[server.PrivateKeyPath].data) != "old-key" {
|
||||
t.Fatalf("配置校验失败后旧证书未完整恢复:%+v", client.files)
|
||||
}
|
||||
for path := range client.files {
|
||||
if strings.Contains(path, ".scert-tmp-") || strings.Contains(path, ".scert-backup-") {
|
||||
t.Fatalf("配置校验回滚后不应残留临时文件或备份文件:%s", path)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeployReportsRollbackFailure(t *testing.T) {
|
||||
client := newMemoryClient()
|
||||
client.runResult.ExitCode = 1
|
||||
client.runResults = []CommandResult{{ExitCode: 0}, {ExitCode: 1}}
|
||||
client.restoreError = true
|
||||
server := testServer("server-1")
|
||||
client.files[server.CertificatePath] = memoryFile{data: []byte("old-cert"), mode: 0o644}
|
||||
|
||||
@@ -19,8 +19,9 @@ type SecretReader interface {
|
||||
}
|
||||
|
||||
type SSHFactory struct {
|
||||
Secrets SecretReader
|
||||
Timeout time.Duration
|
||||
Secrets SecretReader
|
||||
Timeout time.Duration
|
||||
HostKeyAlgorithms []string
|
||||
}
|
||||
|
||||
func (f SSHFactory) Connect(ctx context.Context, server Server) (Client, error) {
|
||||
@@ -53,29 +54,16 @@ func (f SSHFactory) Connect(ctx context.Context, server Server) (Client, error)
|
||||
if timeout <= 0 {
|
||||
timeout = 15 * time.Second
|
||||
}
|
||||
address := net.JoinHostPort(server.Address, fmt.Sprintf("%d", server.Port))
|
||||
dialer := net.Dialer{Timeout: timeout}
|
||||
connection, err := dialer.DialContext(ctx, "tcp", address)
|
||||
algorithms, err := f.secureHostKeyAlgorithms()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("连接 SSH 服务器失败:%w", err)
|
||||
return nil, err
|
||||
}
|
||||
hostKeyCallback := func(hostname string, remote net.Addr, key ssh.PublicKey) error {
|
||||
fingerprint := ssh.FingerprintSHA256(key)
|
||||
if fingerprint != server.HostKeyFingerprint {
|
||||
return fmt.Errorf("SSH 主机指纹不匹配:服务器 %s 返回 %s", server.Name, fingerprint)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
config := &ssh.ClientConfig{
|
||||
User: server.Username, Auth: []ssh.AuthMethod{ssh.PublicKeys(signer)},
|
||||
HostKeyCallback: hostKeyCallback, Timeout: timeout,
|
||||
}
|
||||
clientConn, channels, requests, err := ssh.NewClientConn(connection, address, config)
|
||||
timeoutContext, cancel := context.WithTimeout(ctx, timeout)
|
||||
defer cancel()
|
||||
sshClient, err := connectSSHClient(timeoutContext, server, signer, algorithms)
|
||||
if err != nil {
|
||||
_ = connection.Close()
|
||||
return nil, fmt.Errorf("SSH 握手失败:%w", err)
|
||||
return nil, err
|
||||
}
|
||||
sshClient := ssh.NewClient(clientConn, channels, requests)
|
||||
sftpClient, err := sftp.NewClient(sshClient)
|
||||
if err != nil {
|
||||
_ = sshClient.Close()
|
||||
@@ -84,6 +72,107 @@ func (f SSHFactory) Connect(ctx context.Context, server Server) (Client, error)
|
||||
return &sshClientAdapter{ssh: sshClient, sftp: sftpClient}, nil
|
||||
}
|
||||
|
||||
func (f SSHFactory) secureHostKeyAlgorithms() ([]string, error) {
|
||||
supported := ssh.SupportedAlgorithms().HostKeys
|
||||
if len(f.HostKeyAlgorithms) == 0 {
|
||||
return append([]string(nil), supported...), nil
|
||||
}
|
||||
supportedSet := make(map[string]struct{}, len(supported))
|
||||
for _, algorithm := range supported {
|
||||
supportedSet[algorithm] = struct{}{}
|
||||
}
|
||||
algorithms := make([]string, 0, len(f.HostKeyAlgorithms))
|
||||
seen := make(map[string]struct{}, len(f.HostKeyAlgorithms))
|
||||
for _, algorithm := range f.HostKeyAlgorithms {
|
||||
algorithm = strings.TrimSpace(algorithm)
|
||||
if _, ok := supportedSet[algorithm]; !ok {
|
||||
continue
|
||||
}
|
||||
if _, ok := seen[algorithm]; ok {
|
||||
continue
|
||||
}
|
||||
seen[algorithm] = struct{}{}
|
||||
algorithms = append(algorithms, algorithm)
|
||||
}
|
||||
if len(algorithms) == 0 {
|
||||
return nil, errors.New("SSH 主机密钥算法列表不包含受支持的安全算法")
|
||||
}
|
||||
return algorithms, nil
|
||||
}
|
||||
|
||||
func connectSSHClient(
|
||||
ctx context.Context,
|
||||
server Server,
|
||||
signer ssh.Signer,
|
||||
algorithms []string,
|
||||
) (*ssh.Client, error) {
|
||||
address := net.JoinHostPort(server.Address, fmt.Sprintf("%d", server.Port))
|
||||
var mismatchErrors []string
|
||||
for _, algorithm := range algorithms {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return nil, fmt.Errorf("连接 SSH 服务器超时:%w", err)
|
||||
}
|
||||
connection, err := (&net.Dialer{}).DialContext(ctx, "tcp", address)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("连接 SSH 服务器失败:%w", err)
|
||||
}
|
||||
if deadline, ok := ctx.Deadline(); ok {
|
||||
if err := connection.SetDeadline(deadline); err != nil {
|
||||
_ = connection.Close()
|
||||
return nil, fmt.Errorf("设置 SSH 连接超时失败:%w", err)
|
||||
}
|
||||
}
|
||||
hostKeyMatched := false
|
||||
hostKeyMismatch := ""
|
||||
config := &ssh.ClientConfig{
|
||||
User: server.Username,
|
||||
Auth: []ssh.AuthMethod{ssh.PublicKeys(signer)},
|
||||
HostKeyAlgorithms: []string{algorithm},
|
||||
HostKeyCallback: func(_ string, _ net.Addr, key ssh.PublicKey) error {
|
||||
fingerprint := ssh.FingerprintSHA256(key)
|
||||
if fingerprint != server.HostKeyFingerprint {
|
||||
hostKeyMismatch = fmt.Sprintf("%s 返回 %s", algorithm, fingerprint)
|
||||
return fmt.Errorf("SSH 主机指纹不匹配:服务器 %s %s", server.Name, hostKeyMismatch)
|
||||
}
|
||||
hostKeyMatched = true
|
||||
return nil
|
||||
},
|
||||
}
|
||||
clientConn, channels, requests, handshakeErr := ssh.NewClientConn(connection, address, config)
|
||||
if handshakeErr == nil {
|
||||
if err := connection.SetDeadline(time.Time{}); err != nil {
|
||||
_ = clientConn.Close()
|
||||
return nil, fmt.Errorf("清除 SSH 连接超时失败:%w", err)
|
||||
}
|
||||
return ssh.NewClient(clientConn, channels, requests), nil
|
||||
}
|
||||
_ = connection.Close()
|
||||
if hostKeyMatched {
|
||||
return nil, fmt.Errorf("SSH 握手失败:%w", handshakeErr)
|
||||
}
|
||||
if hostKeyMismatch != "" {
|
||||
mismatchErrors = append(mismatchErrors, hostKeyMismatch)
|
||||
continue
|
||||
}
|
||||
var negotiationError *ssh.AlgorithmNegotiationError
|
||||
if errors.As(handshakeErr, &negotiationError) && negotiationError.What == "host key" {
|
||||
continue
|
||||
}
|
||||
return nil, fmt.Errorf("SSH 握手失败:%w", handshakeErr)
|
||||
}
|
||||
if err := ctx.Err(); err != nil {
|
||||
return nil, fmt.Errorf("连接 SSH 服务器超时:%w", err)
|
||||
}
|
||||
if len(mismatchErrors) == 0 {
|
||||
return nil, fmt.Errorf("SSH 主机指纹不匹配:服务器 %s 未提供已登记的主机密钥", server.Name)
|
||||
}
|
||||
return nil, fmt.Errorf(
|
||||
"SSH 主机指纹不匹配:服务器 %s 未提供已登记的主机密钥;已校验 %s",
|
||||
server.Name,
|
||||
strings.Join(mismatchErrors, ";"),
|
||||
)
|
||||
}
|
||||
|
||||
type sshClientAdapter struct {
|
||||
ssh *ssh.Client
|
||||
sftp *sftp.Client
|
||||
|
||||
@@ -0,0 +1,335 @@
|
||||
package deployment
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/ecdsa"
|
||||
"crypto/ed25519"
|
||||
"crypto/elliptic"
|
||||
"crypto/rand"
|
||||
"encoding/pem"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/pkg/sftp"
|
||||
"golang.org/x/crypto/ssh"
|
||||
)
|
||||
|
||||
func TestSSHFactoryConnectsUsingRegisteredHostKeyAcrossAlgorithms(t *testing.T) {
|
||||
clientSigner, privateKey := newTestSSHSigner(t)
|
||||
ecdsaHostSigner := newTestECDSAHostSigner(t)
|
||||
ed25519HostSigner, _ := newTestSSHSigner(t)
|
||||
server := startTestSSHServer(t, func(key ssh.PublicKey) error {
|
||||
if !bytes.Equal(key.Marshal(), clientSigner.PublicKey().Marshal()) {
|
||||
return errors.New("测试客户端公钥不匹配")
|
||||
}
|
||||
return nil
|
||||
}, ecdsaHostSigner, ed25519HostSigner)
|
||||
|
||||
factory := SSHFactory{
|
||||
Secrets: staticSecretReader{
|
||||
"secret://ssh/hostkey-fallback": {"private_key": privateKey},
|
||||
},
|
||||
Timeout: 2 * time.Second,
|
||||
HostKeyAlgorithms: []string{
|
||||
ssh.KeyAlgoECDSA256,
|
||||
ssh.KeyAlgoED25519,
|
||||
},
|
||||
}
|
||||
client, err := factory.Connect(t.Context(), testSSHServerModel(
|
||||
server,
|
||||
"secret://ssh/hostkey-fallback",
|
||||
ssh.FingerprintSHA256(ed25519HostSigner.PublicKey()),
|
||||
))
|
||||
if err != nil {
|
||||
t.Fatalf("应在 ECDSA 指纹不匹配后使用 ED25519 主机密钥连接:%v", err)
|
||||
}
|
||||
defer client.Close()
|
||||
if server.accepted.Load() != 2 {
|
||||
t.Fatalf("应分别尝试两个主机密钥算法,实际连接次数:%d", server.accepted.Load())
|
||||
}
|
||||
if exists, err := client.Exists(t.Context(), "."); err != nil || !exists {
|
||||
t.Fatalf("SFTP 连接不可用:exists=%t err=%v", exists, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSSHFactorySkipsUnavailableSafeHostKeyAlgorithm(t *testing.T) {
|
||||
clientSigner, privateKey := newTestSSHSigner(t)
|
||||
ed25519HostSigner, _ := newTestSSHSigner(t)
|
||||
server := startTestSSHServer(t, func(key ssh.PublicKey) error {
|
||||
if !bytes.Equal(key.Marshal(), clientSigner.PublicKey().Marshal()) {
|
||||
return errors.New("测试客户端公钥不匹配")
|
||||
}
|
||||
return nil
|
||||
}, ed25519HostSigner)
|
||||
|
||||
factory := SSHFactory{
|
||||
Secrets: staticSecretReader{
|
||||
"secret://ssh/hostkey-unavailable": {"private_key": privateKey},
|
||||
},
|
||||
Timeout: 2 * time.Second,
|
||||
HostKeyAlgorithms: []string{
|
||||
ssh.KeyAlgoECDSA256,
|
||||
ssh.KeyAlgoED25519,
|
||||
},
|
||||
}
|
||||
client, err := factory.Connect(t.Context(), testSSHServerModel(
|
||||
server,
|
||||
"secret://ssh/hostkey-unavailable",
|
||||
ssh.FingerprintSHA256(ed25519HostSigner.PublicKey()),
|
||||
))
|
||||
if err != nil {
|
||||
t.Fatalf("不可用的安全主机密钥算法应被跳过:%v", err)
|
||||
}
|
||||
client.Close()
|
||||
if server.accepted.Load() != 2 {
|
||||
t.Fatalf("应在算法协商失败后尝试下一种安全算法,实际连接次数:%d", server.accepted.Load())
|
||||
}
|
||||
}
|
||||
func TestSSHFactoryRejectsUnregisteredHostKeysAcrossAlgorithms(t *testing.T) {
|
||||
clientSigner, privateKey := newTestSSHSigner(t)
|
||||
ecdsaHostSigner := newTestECDSAHostSigner(t)
|
||||
ed25519HostSigner, _ := newTestSSHSigner(t)
|
||||
server := startTestSSHServer(t, func(key ssh.PublicKey) error {
|
||||
if !bytes.Equal(key.Marshal(), clientSigner.PublicKey().Marshal()) {
|
||||
return errors.New("测试客户端公钥不匹配")
|
||||
}
|
||||
return nil
|
||||
}, ecdsaHostSigner, ed25519HostSigner)
|
||||
|
||||
factory := SSHFactory{
|
||||
Secrets: staticSecretReader{
|
||||
"secret://ssh/hostkey-reject": {"private_key": privateKey},
|
||||
},
|
||||
Timeout: 2 * time.Second,
|
||||
HostKeyAlgorithms: []string{
|
||||
ssh.KeyAlgoECDSA256,
|
||||
ssh.KeyAlgoED25519,
|
||||
},
|
||||
}
|
||||
_, err := factory.Connect(t.Context(), testSSHServerModel(
|
||||
server,
|
||||
"secret://ssh/hostkey-reject",
|
||||
"SHA256:unregistered-test-host-key",
|
||||
))
|
||||
if err == nil || !strings.Contains(err.Error(), "SSH 主机指纹不匹配") {
|
||||
t.Fatalf("未登记的主机指纹必须被拒绝:%v", err)
|
||||
}
|
||||
if !strings.Contains(err.Error(), ssh.KeyAlgoECDSA256) || !strings.Contains(err.Error(), ssh.KeyAlgoED25519) {
|
||||
t.Fatalf("错误应包含已经安全校验的主机密钥算法:%v", err)
|
||||
}
|
||||
if server.accepted.Load() != 2 {
|
||||
t.Fatalf("错误指纹应校验两个可用算法,实际连接次数:%d", server.accepted.Load())
|
||||
}
|
||||
}
|
||||
|
||||
func TestSSHFactoryStopsAfterMatchedHostKeyAuthenticationFailure(t *testing.T) {
|
||||
_, privateKey := newTestSSHSigner(t)
|
||||
ecdsaHostSigner := newTestECDSAHostSigner(t)
|
||||
ed25519HostSigner, _ := newTestSSHSigner(t)
|
||||
server := startTestSSHServer(t, func(ssh.PublicKey) error {
|
||||
return errors.New("测试认证拒绝")
|
||||
}, ecdsaHostSigner, ed25519HostSigner)
|
||||
|
||||
factory := SSHFactory{
|
||||
Secrets: staticSecretReader{
|
||||
"secret://ssh/auth-reject": {"private_key": privateKey},
|
||||
},
|
||||
Timeout: 2 * time.Second,
|
||||
HostKeyAlgorithms: []string{
|
||||
ssh.KeyAlgoECDSA256,
|
||||
ssh.KeyAlgoED25519,
|
||||
},
|
||||
}
|
||||
_, err := factory.Connect(t.Context(), testSSHServerModel(
|
||||
server,
|
||||
"secret://ssh/auth-reject",
|
||||
ssh.FingerprintSHA256(ecdsaHostSigner.PublicKey()),
|
||||
))
|
||||
if err == nil || !strings.Contains(err.Error(), "SSH 握手失败") {
|
||||
t.Fatalf("主机指纹匹配后的认证失败必须直接返回:%v", err)
|
||||
}
|
||||
if strings.Contains(err.Error(), "SSH 主机指纹不匹配") {
|
||||
t.Fatalf("认证失败不得继续尝试其他主机密钥算法:%v", err)
|
||||
}
|
||||
if server.accepted.Load() != 1 {
|
||||
t.Fatalf("认证失败后不得继续重连,实际连接次数:%d", server.accepted.Load())
|
||||
}
|
||||
}
|
||||
|
||||
func TestSSHFactoryFiltersUnsupportedAndDuplicateHostKeyAlgorithms(t *testing.T) {
|
||||
factory := SSHFactory{HostKeyAlgorithms: []string{
|
||||
"ssh-dss",
|
||||
ssh.KeyAlgoED25519,
|
||||
ssh.KeyAlgoED25519,
|
||||
}}
|
||||
algorithms, err := factory.secureHostKeyAlgorithms()
|
||||
if err != nil {
|
||||
t.Fatalf("安全算法过滤失败:%v", err)
|
||||
}
|
||||
if len(algorithms) != 1 || algorithms[0] != ssh.KeyAlgoED25519 {
|
||||
t.Fatalf("算法过滤结果不正确:%v", algorithms)
|
||||
}
|
||||
factory.HostKeyAlgorithms = []string{"ssh-dss"}
|
||||
if _, err := factory.secureHostKeyAlgorithms(); err == nil {
|
||||
t.Fatal("仅包含不安全或不支持算法时必须拒绝")
|
||||
}
|
||||
}
|
||||
|
||||
type testSSHServer struct {
|
||||
listener net.Listener
|
||||
accepted atomic.Int32
|
||||
host string
|
||||
port int
|
||||
config *ssh.ServerConfig
|
||||
}
|
||||
|
||||
func startTestSSHServer(
|
||||
t *testing.T,
|
||||
authorize func(ssh.PublicKey) error,
|
||||
hostSigners ...ssh.Signer,
|
||||
) *testSSHServer {
|
||||
t.Helper()
|
||||
config := &ssh.ServerConfig{
|
||||
PublicKeyCallback: func(_ ssh.ConnMetadata, key ssh.PublicKey) (*ssh.Permissions, error) {
|
||||
return nil, authorize(key)
|
||||
},
|
||||
}
|
||||
for _, signer := range hostSigners {
|
||||
config.AddHostKey(signer)
|
||||
}
|
||||
listener, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatalf("启动测试 SSH 服务失败:%v", err)
|
||||
}
|
||||
host, portText, err := net.SplitHostPort(listener.Addr().String())
|
||||
if err != nil {
|
||||
listener.Close()
|
||||
t.Fatalf("解析测试 SSH 地址失败:%v", err)
|
||||
}
|
||||
port, err := strconv.Atoi(portText)
|
||||
if err != nil {
|
||||
listener.Close()
|
||||
t.Fatalf("解析测试 SSH 端口失败:%v", err)
|
||||
}
|
||||
server := &testSSHServer{
|
||||
listener: listener,
|
||||
host: host,
|
||||
port: port,
|
||||
config: config,
|
||||
}
|
||||
t.Cleanup(func() {
|
||||
listener.Close()
|
||||
})
|
||||
go server.serve()
|
||||
return server
|
||||
}
|
||||
|
||||
func (s *testSSHServer) serve() {
|
||||
for {
|
||||
connection, err := s.listener.Accept()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
s.accepted.Add(1)
|
||||
go s.serveConnection(connection)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *testSSHServer) serveConnection(connection net.Conn) {
|
||||
defer connection.Close()
|
||||
_, channels, requests, err := ssh.NewServerConn(connection, s.config)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
go ssh.DiscardRequests(requests)
|
||||
for channelRequest := range channels {
|
||||
if channelRequest.ChannelType() != "session" {
|
||||
channelRequest.Reject(ssh.UnknownChannelType, "session channel required")
|
||||
continue
|
||||
}
|
||||
channel, requests, err := channelRequest.Accept()
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
go serveTestSFTP(channel, requests)
|
||||
}
|
||||
}
|
||||
|
||||
func serveTestSFTP(channel ssh.Channel, requests <-chan *ssh.Request) {
|
||||
defer channel.Close()
|
||||
for request := range requests {
|
||||
if request.Type != "subsystem" {
|
||||
request.Reply(false, nil)
|
||||
continue
|
||||
}
|
||||
var subsystem struct {
|
||||
Name string
|
||||
}
|
||||
if err := ssh.Unmarshal(request.Payload, &subsystem); err != nil || subsystem.Name != "sftp" {
|
||||
request.Reply(false, nil)
|
||||
continue
|
||||
}
|
||||
if err := request.Reply(true, nil); err != nil {
|
||||
return
|
||||
}
|
||||
server, err := sftp.NewServer(channel)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
_ = server.Serve()
|
||||
_ = server.Close()
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
func newTestSSHSigner(t *testing.T) (ssh.Signer, string) {
|
||||
t.Helper()
|
||||
_, privateKey, err := ed25519.GenerateKey(rand.Reader)
|
||||
if err != nil {
|
||||
t.Fatalf("生成测试 ED25519 密钥失败:%v", err)
|
||||
}
|
||||
signer, err := ssh.NewSignerFromKey(privateKey)
|
||||
if err != nil {
|
||||
t.Fatalf("创建测试 SSH 签名器失败:%v", err)
|
||||
}
|
||||
block, err := ssh.MarshalPrivateKey(privateKey, "scert-ssh-test")
|
||||
if err != nil {
|
||||
t.Fatalf("编码测试 SSH 私钥失败:%v", err)
|
||||
}
|
||||
return signer, string(pem.EncodeToMemory(block))
|
||||
}
|
||||
|
||||
func newTestECDSAHostSigner(t *testing.T) ssh.Signer {
|
||||
t.Helper()
|
||||
privateKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
|
||||
if err != nil {
|
||||
t.Fatalf("生成测试 ECDSA 主机密钥失败:%v", err)
|
||||
}
|
||||
signer, err := ssh.NewSignerFromKey(privateKey)
|
||||
if err != nil {
|
||||
t.Fatalf("创建测试 ECDSA 主机签名器失败:%v", err)
|
||||
}
|
||||
return signer
|
||||
}
|
||||
|
||||
func testSSHServerModel(server *testSSHServer, privateKeyRef, fingerprint string) Server {
|
||||
return Server{
|
||||
ID: fmt.Sprintf("server-%d", server.port),
|
||||
Name: "多主机密钥测试服务器",
|
||||
Address: server.host,
|
||||
Port: server.port,
|
||||
Username: "deploy",
|
||||
PrivateKeyRef: privateKeyRef,
|
||||
HostKeyFingerprint: fingerprint,
|
||||
CertificatePath: "/tmp/scert-test-cert.pem",
|
||||
PrivateKeyPath: "/tmp/scert-test-key.pem",
|
||||
CertificateChainPath: "/tmp/scert-test-fullchain.pem",
|
||||
WebServer: WebServerNginx,
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user