Skip to content

Commit

Permalink
ssh/knownhosts: fix bracket normalisation
Browse files Browse the repository at this point in the history
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
  • Loading branch information
pacien committed Aug 23, 2023
1 parent b4ddeed commit 71680b0
Show file tree
Hide file tree
Showing 2 changed files with 4 additions and 6 deletions.
4 changes: 1 addition & 3 deletions ssh/knownhosts/knownhosts.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Expand Down
6 changes: 3 additions & 3 deletions ssh/knownhosts/knownhosts_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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)
Expand Down

0 comments on commit 71680b0

Please sign in to comment.