From 71680b0c7947d9850b4a71eae80258056a3db54a Mon Sep 17 00:00:00 2001 From: pacien Date: Wed, 23 Aug 2023 19:41:11 +0200 Subject: [PATCH] ssh/knownhosts: fix bracket normalisation 1. When using the bracketed syntax, the port is mandatory, even if it's the default one. Otherwise, OpenSSH rejects it with: "address [abcd:abcd:abcd:abcd]: missing port in address". See sshd(8): SSH_KNOWN_HOSTS FILE FORMAT. 2. Brackets are not necessary when using the default port, even for IPv6 addresses. Fixes golang/go#53463 --- ssh/knownhosts/knownhosts.go | 4 +--- ssh/knownhosts/knownhosts_test.go | 6 +++--- 2 files changed, 4 insertions(+), 6 deletions(-) diff --git a/ssh/knownhosts/knownhosts.go b/ssh/knownhosts/knownhosts.go index 7376a8dff2..29c6005b26 100644 --- a/ssh/knownhosts/knownhosts.go +++ b/ssh/knownhosts/knownhosts.go @@ -439,14 +439,12 @@ func New(files ...string) (ssh.HostKeyCallback, error) { func Normalize(address string) string { host, port, err := net.SplitHostPort(address) if err != nil { - host = address + host = strings.Trim(address, "[]") port = "22" } entry := host if port != "22" { entry = "[" + entry + "]:" + port - } else if strings.Contains(host, ":") && !strings.HasPrefix(host, "[") { - entry = "[" + entry + "]" } return entry } diff --git a/ssh/knownhosts/knownhosts_test.go b/ssh/knownhosts/knownhosts_test.go index 464dd59249..b012d65357 100644 --- a/ssh/knownhosts/knownhosts_test.go +++ b/ssh/knownhosts/knownhosts_test.go @@ -247,7 +247,7 @@ func TestLine(t *testing.T) { "server.org": "server.org " + edKeyStr, "server.org:22": "server.org " + edKeyStr, "server.org:23": "[server.org]:23 " + edKeyStr, - "[c629:1ec4:102:304:102:304:102:304]:22": "[c629:1ec4:102:304:102:304:102:304] " + edKeyStr, + "[c629:1ec4:102:304:102:304:102:304]:22": "c629:1ec4:102:304:102:304:102:304 " + edKeyStr, "[c629:1ec4:102:304:102:304:102:304]:23": "[c629:1ec4:102:304:102:304:102:304]:23 " + edKeyStr, } { if got := Line([]string{in}, edKey); got != want { @@ -326,8 +326,8 @@ func TestNormalize(t *testing.T) { "[127.0.0.1]:23": "[127.0.0.1]:23", "127.0.0.1:23": "[127.0.0.1]:23", "[a.b.c]:22": "a.b.c", - "[abcd:abcd:abcd:abcd]": "[abcd:abcd:abcd:abcd]", - "[abcd:abcd:abcd:abcd]:22": "[abcd:abcd:abcd:abcd]", + "[abcd:abcd:abcd:abcd]": "abcd:abcd:abcd:abcd", + "[abcd:abcd:abcd:abcd]:22": "abcd:abcd:abcd:abcd", "[abcd:abcd:abcd:abcd]:23": "[abcd:abcd:abcd:abcd]:23", } { got := Normalize(in)