Skip to content
New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

ssh: add support for hashing hostnames in known_hosts #274

Merged
merged 1 commit into from
May 16, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 8 additions & 3 deletions ssh/host_key.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,8 +33,8 @@ import (
// clientHostKeyAlgos defines what HostKey algorithms to be
// used by the ssh client when using `ssh.Dial`. The default is
// empty, which defaults to Golang's preferred HostKey algorithms.
func ScanHostKey(host string, timeout time.Duration, clientHostKeyAlgos []string) ([]byte, error) {
col := &HostKeyCollector{}
func ScanHostKey(host string, timeout time.Duration, clientHostKeyAlgos []string, hashKeys bool) ([]byte, error) {
col := &HostKeyCollector{hashKeys: hashKeys}
config := &ssh.ClientConfig{
HostKeyCallback: col.StoreKey(),
Timeout: timeout,
Expand All @@ -54,6 +54,7 @@ func ScanHostKey(host string, timeout time.Duration, clientHostKeyAlgos []string
// HostKeyCallBack to collect public keys from an SSH server.
type HostKeyCollector struct {
knownKeys []byte
hashKeys bool
}

// StoreKey stores the public key in bytes as returned by the host.
Expand All @@ -62,9 +63,13 @@ type HostKeyCollector struct {
// the algorithm you want to collect.
func (c *HostKeyCollector) StoreKey() ssh.HostKeyCallback {
return func(hostname string, remote net.Addr, key ssh.PublicKey) error {
h := knownhosts.Normalize(hostname)
if c.hashKeys {
h = knownhosts.HashHostname(h)
}
c.knownKeys = append(
c.knownKeys,
fmt.Sprintf("%s %s %s\n", knownhosts.Normalize(hostname), key.Type(), base64.StdEncoding.EncodeToString(key.Marshal()))...,
fmt.Sprintf("%s %s %s\n", h, key.Type(), base64.StdEncoding.EncodeToString(key.Marshal()))...,
)
return nil
}
Expand Down
2 changes: 1 addition & 1 deletion ssh/host_key_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ func TestScanHost(t *testing.T) {

go startSSH(listener, sshConfig)

kh, err := ScanHostKey(serverAddr, 5*time.Second, []string{tt.sshKeyTypeName})
kh, err := ScanHostKey(serverAddr, 5*time.Second, []string{tt.sshKeyTypeName}, false)
if tt.wantErr == "" {
g.Expect(err).NotTo(HaveOccurred())
// Confirm the returned key is of expected type.
Expand Down