From 64212fce8cade07e2a4e6b1a1d10d6acc79d586a Mon Sep 17 00:00:00 2001 From: Pim van Pelt Date: Sun, 13 Jul 2025 22:21:27 +0200 Subject: [PATCH] Twiddle ssh auth, use password before --key-file flag before homedir before agent --- src/main.go | 3 +++ src/ssh.go | 27 ++++++++++++++++++--------- 2 files changed, 21 insertions(+), 9 deletions(-) diff --git a/src/main.go b/src/main.go index 5f17acf..41d6a77 100644 --- a/src/main.go +++ b/src/main.go @@ -84,6 +84,9 @@ func main() { fmt.Printf("Using SSH key: %s\n", keyFile) hasAuth++ } + } else { + fmt.Printf("Using specified SSH key: %s\n", keyFile) + hasAuth++ } if password != "" { fmt.Println("Using --password for authentication") diff --git a/src/ssh.go b/src/ssh.go index d4a6e15..a1e70d0 100644 --- a/src/ssh.go +++ b/src/ssh.go @@ -103,11 +103,6 @@ func (rb *RouterBackup) Connect() error { config.KeyExchanges = finalAlgorithms } - // Note: Cipher overrides disabled - Go SSH library defaults work better - // if ciphers := ssh_config.Get(rb.hostname, "Ciphers"); ciphers != "" { - // config.Ciphers = ... - // } - if macs := ssh_config.Get(rb.hostname, "MACs"); macs != "" { macList := strings.Split(macs, ",") for i, mac := range macList { @@ -126,15 +121,19 @@ func (rb *RouterBackup) Connect() error { config.HostKeyAlgorithms = finalAlgorithms } - // Try SSH agent first if available + // If explicit key file is provided, prioritize it over SSH agent + var keyFileAuth ssh.AuthMethod + var agentAuth ssh.AuthMethod + + // Try SSH agent if available (but don't add to config.Auth yet) if sshAuthSock := os.Getenv("SSH_AUTH_SOCK"); sshAuthSock != "" { if conn, err := net.Dial("unix", sshAuthSock); err == nil { agentClient := agent.NewClient(conn) - config.Auth = []ssh.AuthMethod{ssh.PublicKeysCallback(agentClient.Signers)} + agentAuth = ssh.PublicKeysCallback(agentClient.Signers) } } - // If SSH agent didn't work, try key file + // Try key file if keyFile != "" { // Expand ~ in keyFile path if strings.HasPrefix(keyFile, "~/") { @@ -150,11 +149,21 @@ func (rb *RouterBackup) Connect() error { if err != nil { fmt.Printf("%s: Unable to parse private key: %v\n", rb.hostname, err) } else { - config.Auth = append(config.Auth, ssh.PublicKeys(signer)) + keyFileAuth = ssh.PublicKeys(signer) } } } + // Prioritize auth methods: explicit key file first, then SSH agent + if keyFileAuth != nil { + config.Auth = []ssh.AuthMethod{keyFileAuth} + if agentAuth != nil { + config.Auth = append(config.Auth, agentAuth) + } + } else if agentAuth != nil { + config.Auth = []ssh.AuthMethod{agentAuth} + } + // Fall back to password if available if rb.password != "" { config.Auth = append(config.Auth, ssh.Password(rb.password))