Skip to content

Commit 62fb541

Browse files
committed
ssh/knownhosts: fix hashed hostname component count in error message
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. The existing tests cover the changed code. Signed-off-by: Kimmo Lehto <[email protected]>
1 parent d042a39 commit 62fb541

File tree

2 files changed

+19
-5
lines changed

2 files changed

+19
-5
lines changed

ssh/knownhosts/knownhosts.go

+5-5
Original file line numberDiff line numberDiff line change
@@ -481,17 +481,17 @@ func decodeHash(encoded string) (hashType string, salt, hash []byte, err error)
481481
err = errors.New("knownhosts: hashed host must start with '|'")
482482
return
483483
}
484-
components := strings.Split(encoded, "|")
485-
if len(components) != 4 {
484+
components := strings.Split(encoded[1:], "|")
485+
if len(components) != 3 {
486486
err = fmt.Errorf("knownhosts: got %d components, want 3", len(components))
487487
return
488488
}
489489

490-
hashType = components[1]
491-
if salt, err = base64.StdEncoding.DecodeString(components[2]); err != nil {
490+
hashType = components[0]
491+
if salt, err = base64.StdEncoding.DecodeString(components[1]); err != nil {
492492
return
493493
}
494-
if hash, err = base64.StdEncoding.DecodeString(components[3]); err != nil {
494+
if hash, err = base64.StdEncoding.DecodeString(components[2]); err != nil {
495495
return
496496
}
497497
return

ssh/knownhosts/knownhosts_test.go

+14
Original file line numberDiff line numberDiff line change
@@ -292,13 +292,27 @@ const encodedTestHostnameHash = "|1|IHXZvQMvTcZTUU29+2vXFgx8Frs=|UGccIWfRVDwilMB
292292

293293
func TestHostHash(t *testing.T) {
294294
testHostHash(t, testHostname, encodedTestHostnameHash)
295+
testHostHashDecode(t)
295296
}
296297

297298
func TestHashList(t *testing.T) {
298299
encoded := HashHostname(testHostname)
299300
testHostHash(t, testHostname, encoded)
300301
}
301302

303+
func testHostHashDecode(t *testing.T) {
304+
for in, want := range map[string]string{
305+
"1": "must start with '|'",
306+
"|typ|salt": "got 2 components",
307+
"|typ|salt|hash|extra": "got 4 components",
308+
} {
309+
_, _, _, err := decodeHash(in)
310+
if err == nil || !strings.Contains(err.Error(), want) {
311+
t.Fatalf("decodeHash: expected error to match %q, got %v", want, err)
312+
}
313+
}
314+
}
315+
302316
func testHostHash(t *testing.T, hostname, encoded string) {
303317
typ, salt, hash, err := decodeHash(encoded)
304318
if err != nil {

0 commit comments

Comments
 (0)