Skip to content

Commit de728ea

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 de728ea

File tree

2 files changed

+20
-5
lines changed

2 files changed

+20
-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

+15
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ import (
99
"fmt"
1010
"net"
1111
"reflect"
12+
"strings"
1213
"testing"
1314

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

293294
func TestHostHash(t *testing.T) {
294295
testHostHash(t, testHostname, encodedTestHostnameHash)
296+
testHostHashDecode(t)
295297
}
296298

297299
func TestHashList(t *testing.T) {
298300
encoded := HashHostname(testHostname)
299301
testHostHash(t, testHostname, encoded)
300302
}
301303

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

0 commit comments

Comments
 (0)