CVE-2017-3204 (Go, published 2017-04-04T14:59Z)
Description: value: The Go SSH library (x/crypto/ssh) by default does not verify host keys, facilitating man-in-the-middle attacks. Default behavior changed in commit e4e2799 to require explicitly registering a hostkey verification mechanism.
Severity: MEDIUM (CVSS v3 base score: 8.1)
Weakness: NVD-CWE-noinfo \u2014 Insufficient Information
There is insufficient information about the issue to classify it; details are unkown or unspecified.
Repository: https://github.com/golang/crypto
Files changed:
ssh/agent/client_test.go
ssh/agent/example_test.go
ssh/agent/server_test.go
ssh/certs.go
ssh/client.go
ssh/client_auth_test.go
ssh/client_test.go
ssh/doc.go
ssh/example_test.go
ssh/handshake.go
ssh/handshake_test.go
ssh/session_test.go
ssh/test/cert_test.go
Commit message: ssh: require host key checking in the ClientConfig

This change breaks existing behavior.

Before, a missing ClientConfig.HostKeyCallback would cause host key
checking to be disabled. In this configuration, establishing a
connection to any host just works, so today, most SSH client code in
the wild does not perform any host key checks.

This makes it easy to perform a MITM attack:

* SSH installations that use keyboard-interactive or password
authentication can be attacked with MITM, thereby stealing
passwords.

* Clients that use public-key authentication with agent forwarding are
also vulnerable: the MITM server could allow the login to succeed, and
then immediately ask the agent to authenticate the login to the real
server.

* Clients that use public-key authentication without agent forwarding
are harder to attack unnoticedly: an attacker cannot authenticate the
login to the real server, so it cannot in general present a convincing
server to the victim.

Now, a missing HostKeyCallback will cause the handshake to fail. This
change also provides InsecureIgnoreHostKey() and FixedHostKey(key) as
ready made host checkers.

A simplistic parser for OpenSSH's known_hosts file is given as an
example.  This change does not provide a full-fledged parser, as it
has complexity (wildcards, revocation, hashed addresses) that will
need further consideration.

When introduced, the host checking feature maintained backward
compatibility at the expense of security. We have decided this is not
the right tradeoff for the SSH library.

Fixes golang/go#19767

Change-Id: I45fc7ba9bd1ea29c31ec23f115cdbab99913e814
Reviewed-on: https://go-review.googlesource.com/38701
Run-TryBot: Han-Wen Nienhuys <hanwen@google.com>
TryBot-Result: Gobot Gobot <gobot@golang.org>
Reviewed-by: Brad Fitzpatrick <bradfitz@golang.org>


Vulnerable code:
	conf := ssh.ClientConfig{}
	"os"
        "golang.org/x/crypto/ssh"
        "golang.org/x/crypto/ssh/agent"
        conn, err := net.Dial("unix", socket)
        if err != nil {
                log.Fatalf("net.Dial: %v", err)
        }
	conf := ssh.ClientConfig{}
	HostKeyFallback func(addr string, remote net.Addr, key PublicKey) error
	// HostKeyCallback, if not nil, is called during the cryptographic
	// handshake to validate the server's host key. A nil HostKeyCallback
	// implies that all host keys are accepted.
	HostKeyCallback func(hostname string, remote net.Addr, key PublicKey) error
		User: "user",
		User: user,
		User: user,
	// Service the incoming Channel channel.

	// implementation of AuthMethod via the Auth field in ClientConfig.
	hostKeyCallback func(hostname string, remote net.Addr, key PublicKey) error
	if t.hostKeyCallback != nil {
		err = t.hostKeyCallback(t.dialAddress, t.remoteAddr, hostKey)
		if err != nil {
			return nil, err
		}
		User: "testuser",
		User: "user",
	clientConf := &ClientConfig{}
		User: username(),

Fixed code:
	conf := ssh.ClientConfig{
		HostKeyCallback: ssh.InsecureIgnoreHostKey(),
	}
	"os"
	"golang.org/x/crypto/ssh"
	"golang.org/x/crypto/ssh/agent"
	conn, err := net.Dial("unix", socket)
	if err != nil {
		log.Fatalf("net.Dial: %v", err)
	}
		HostKeyCallback: ssh.InsecureIgnoreHostKey(),
	conf := ssh.ClientConfig{
		HostKeyCallback: ssh.InsecureIgnoreHostKey(),
	}
	HostKeyFallback HostKeyCallback
	"bytes"
	if fullConf.HostKeyCallback == nil {
		c.Close()
		return nil, nil, nil, errors.New("ssh: must specify HostKeyCallback")
	}

// HostKeyCallback is the function type used for verifying server
// keys.  A HostKeyCallback must return nil if the host key is OK, or
// an error to reject it. It receives the hostname as passed to Dial
// or NewClientConn. The remote address is the RemoteAddr of the
// net.Conn underlying the the SSH connection.
type HostKeyCallback func(hostname string, remote net.Addr, key PublicKey) error

	// HostKeyCallback is called during the cryptographic
	// handshake to validate the server's host key. The client
	// configuration must supply this callback for the connection
	// to succeed. The functions InsecureIgnoreHostKey or
	// FixedHostKey can be used for simplistic host key checks.
	HostKeyCallback HostKeyCallback

// InsecureIgnoreHostKey returns a function that can be used for
// ClientConfig.HostKeyCallback to accept any host key. It should
// not be used for production code.
func InsecureIgnoreHostKey() HostKeyCallback {
	return func(hostname string, remote net.Addr, key PublicKey) error {
		return nil
	}
}

type fixedHostKey struct {
	key PublicKey
}

func (f *fixedHostKey) check(hostname string, remote net.Addr, key PublicKey) error {
	if f.key == nil {
		return fmt.Errorf("ssh: required host key was nil")
	}
	if !bytes.Equal(key.Marshal(), f.key.Marshal()) {
		return fmt.Errorf("ssh: host key mismatch")
	}
	return nil
}

// FixedHostKey returns a function for use in
// ClientConfig.HostKeyCallback to accept only a specific host key.
func FixedHostKey(key PublicKey) HostKeyCallback {
	hk := &fixedHostKey{key}
	return hk.check
}
		HostKeyCallback: InsecureIgnoreHostKey(),
		HostKeyCallback: InsecureIgnoreHostKey(),
		HostKeyCallback: InsecureIgnoreHostKey(),
		HostKeyCallback: InsecureIgnoreHostKey(),
		HostKeyCallback: InsecureIgnoreHostKey(),
		HostKeyCallback: InsecureIgnoreHostKey(),
			HostKeyCallback: InsecureIgnoreHostKey(),
		HostKeyCallback: InsecureIgnoreHostKey(),
		User:            "user",
		HostKeyCallback: InsecureIgnoreHostKey(),
		HostKeyCallback: InsecureIgnoreHostKey(),
		HostKeyCallback: InsecureIgnoreHostKey(),
		HostKeyCallback: InsecureIgnoreHostKey(),
		User:            user,
		User:            user,
		HostKeyCallback: InsecureIgnoreHostKey(),
	"strings"
	config.HostKeyCallback = InsecureIgnoreHostKey()

func TestHostKeyCheck(t *testing.T) {
	for _, tt := range []struct {
		name      string
		wantError string
		key       PublicKey
	}{
		{"no callback", "must specify HostKeyCallback", nil},
		{"correct key", "", testSigners["rsa"].PublicKey()},
		{"mismatch", "mismatch", testSigners["ecdsa"].PublicKey()},
	} {
		c1, c2, err := netPipe()
		if err != nil {
			t.Fatalf("netPipe: %v", err)
		}
		defer c1.Close()
		defer c2.Close()
		serverConf := &ServerConfig{
			NoClientAuth: true,
		}
		serverConf.AddHostKey(testSigners["rsa"])

		go NewServerConn(c1, serverConf)
		clientConf := ClientConfig{
			User: "user",
		}
		if tt.key != nil {
			clientConf.HostKeyCallback = FixedHostKey(tt.key)
		}

		_, _, _, err = NewClientConn(c2, "", &clientConf)
		if err != nil {
			if tt.wantError == "" || !strings.Contains(err.Error(), tt.wantError) {
				t.Errorf("%s: got error %q, missing %q", err.Error(), tt.wantError)
			}
		} else if tt.wantError != "" {
			t.Errorf("%s: succeeded, but want error string %q", tt.name, tt.wantError)
		}
	}
}

This package does not fall under the stability promise of the Go language itself,
so its API may be changed when pressing needs arise.
	"bufio"
	"os"
	"path/filepath"
	"strings"
func ExampleHostKeyCheck() {
	// Every client must provide a host key check.  Here is a
	// simple-minded parse of OpenSSH's known_hosts file
	host := "hostname"
	file, err := os.Open(filepath.Join(os.Getenv("HOME"), ".ssh", "known_hosts"))
	if err != nil {
		log.Fatal(err)
	}
	defer file.Close()

	scanner := bufio.NewScanner(file)
	var hostKey ssh.PublicKey
	for scanner.Scan() {
		fields := strings.Split(scanner.Text(), " ")
		if len(fields) != 3 {
			continue
		}
		if strings.Contains(fields[0], host) {
			var err error
			hostKey, _, _, _, err = ssh.ParseAuthorizedKey(scanner.Bytes())
			if err != nil {
				log.Fatalf("error parsing %q: %v", fields[2], err)
			}
			break
		}
	}

	if hostKey == nil {
		log.Fatalf("no hostkey for %s", host)
	}

	config := ssh.ClientConfig{
		User:            os.Getenv("USER"),
		HostKeyCallback: ssh.FixedHostKey(hostKey),
	}

	_, err = ssh.Dial("tcp", host+":22", &config)
	log.Println(err)
}

	var hostKey ssh.PublicKey
	// implementation of AuthMethod via the Auth field in ClientConfig,
	// and provide a HostKeyCallback.
		HostKeyCallback: ssh.FixedHostKey(hostKey),
	var hostKey ssh.PublicKey
		HostKeyCallback: ssh.FixedHostKey(hostKey),
	var hostKey ssh.PublicKey
		HostKeyCallback: ssh.FixedHostKey(hostKey),
	var hostKey ssh.PublicKey
		HostKeyCallback: ssh.FixedHostKey(hostKey),
	hostKeyCallback HostKeyCallback
	err = t.hostKeyCallback(t.dialAddress, t.remoteAddr, hostKey)
	if err != nil {
		return nil, err
	clientConn.hostKeyCallback = InsecureIgnoreHostKey()
		User:            "testuser",
		HostKeyCallback: InsecureIgnoreHostKey(),
		HostKeyCallback: InsecureIgnoreHostKey(),
		User:            "user",
	clientConf := &ClientConfig{
		HostKeyCallback: InsecureIgnoreHostKey(),
	}
		User:            username(),
		HostKeyCallback: ssh.InsecureIgnoreHostKey(),