Skip to content

Commit

Permalink
ssh/knownhosts: fix hashed hostname component count in error message
Browse files Browse the repository at this point in the history
Correct the component splitting in the nextWord function to omit the
initial empty element when decoding the pipe-separated hostname hash.

Previously, the error message incorrectly counted this empty element,
leading to misleading errors like:

"knownhosts: got 3 components, want 3"

This change makes the component split start from index 1.

Tests for the error messages were added.

Signed-off-by: Kimmo Lehto <[email protected]>
  • Loading branch information
kke committed Apr 29, 2024
1 parent d042a39 commit 521524c
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 5 deletions.
10 changes: 5 additions & 5 deletions ssh/knownhosts/knownhosts.go
Original file line number Diff line number Diff line change
Expand Up @@ -481,17 +481,17 @@ func decodeHash(encoded string) (hashType string, salt, hash []byte, err error)
err = errors.New("knownhosts: hashed host must start with '|'")
return
}
components := strings.Split(encoded, "|")
if len(components) != 4 {
components := strings.Split(encoded[1:], "|")
if len(components) != 3 {
err = fmt.Errorf("knownhosts: got %d components, want 3", len(components))
return
}

hashType = components[1]
if salt, err = base64.StdEncoding.DecodeString(components[2]); err != nil {
hashType = components[0]
if salt, err = base64.StdEncoding.DecodeString(components[1]); err != nil {
return
}
if hash, err = base64.StdEncoding.DecodeString(components[3]); err != nil {
if hash, err = base64.StdEncoding.DecodeString(components[2]); err != nil {
return
}
return
Expand Down
15 changes: 15 additions & 0 deletions ssh/knownhosts/knownhosts_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import (
"fmt"
"net"
"reflect"
"strings"
"testing"

"golang.org/x/crypto/ssh"
Expand Down Expand Up @@ -292,13 +293,27 @@ const encodedTestHostnameHash = "|1|IHXZvQMvTcZTUU29+2vXFgx8Frs=|UGccIWfRVDwilMB

func TestHostHash(t *testing.T) {
testHostHash(t, testHostname, encodedTestHostnameHash)
testHostHashDecode(t)
}

func TestHashList(t *testing.T) {
encoded := HashHostname(testHostname)
testHostHash(t, testHostname, encoded)
}

func testHostHashDecode(t *testing.T) {
for in, want := range map[string]string{
"1": "must start with '|'",
"|typ|salt": "got 2 components",
"|typ|salt|hash|extra": "got 4 components",
} {
_, _, _, err := decodeHash(in)
if err == nil || !strings.Contains(err.Error(), want) {
t.Fatalf("decodeHash: expected error to match %q, got %v", want, err)
}
}
}

func testHostHash(t *testing.T, hostname, encoded string) {
typ, salt, hash, err := decodeHash(encoded)
if err != nil {
Expand Down

0 comments on commit 521524c

Please sign in to comment.