Skip to content

Commit

Permalink
update KnownKey.Matches to initialize it's own hasher
Browse files Browse the repository at this point in the history
Previously, KnownKey.Matches() accepted a SHA256 hasher as an argument,
which could lead to unintended bugs when calling it in a loop. This
eliminates that, by initializing a new hasher itself instead of relying
on the caller for the same.
Enables us to fix a regression in the source-controller: fluxcd/image-automation-controller#378

Signed-off-by: Sanskar Jaiswal <jaiswalsanskar078@gmail.com>
  • Loading branch information
aryan9600 committed Jun 8, 2022
1 parent 2149190 commit 64591ea
Show file tree
Hide file tree
Showing 2 changed files with 4 additions and 5 deletions.
5 changes: 3 additions & 2 deletions ssh/knownhosts/known_key.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,9 @@ import (
"bytes"
"crypto/hmac"
"crypto/sha1"
"crypto/sha256"
"encoding/base64"
"fmt"
"hash"
"io"
"strings"

Expand Down Expand Up @@ -67,10 +67,11 @@ func ParseKnownHosts(s string) ([]KnownKey, error) {

// Matches checks if the specified host is present and if the fingerprint matches
// the present public key key.
func (k KnownKey) Matches(host string, fingerprint []byte, hasher hash.Hash) bool {
func (k KnownKey) Matches(host string, fingerprint []byte) bool {
if !containsHost(k.hosts, host) {
return false
}
hasher := sha256.New()
hasher.Write(k.key.Marshal())
return bytes.Equal(hasher.Sum(nil), fingerprint)
}
Expand Down
4 changes: 1 addition & 3 deletions ssh/knownhosts/known_key_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@ limitations under the License.
package knownhosts

import (
"crypto/sha256"
"encoding/base64"
"testing"

Expand Down Expand Up @@ -91,7 +90,6 @@ func Test_matchHashedHost(t *testing.T) {
}

func Test_parseKnownHosts_matches(t *testing.T) {
hasher := sha256.New()
tests := []struct {
name string
fingerprint []byte
Expand All @@ -117,7 +115,7 @@ func Test_parseKnownHosts_matches(t *testing.T) {
t.Error(err)
return
}
matches := knownKeys[0].Matches("github.com", tt.fingerprint, hasher)
matches := knownKeys[0].Matches("github.com", tt.fingerprint)
g.Expect(matches).To(Equal(tt.wantMatches))
})
}
Expand Down

0 comments on commit 64591ea

Please sign in to comment.