github.com/zebozhuang/go@v0.0.0-20200207033046-f8a98f6f5c5d/src/crypto/tls/handshake_server_test.go (about)

     1  // Copyright 2009 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package tls
     6  
     7  import (
     8  	"bytes"
     9  	"crypto/ecdsa"
    10  	"crypto/elliptic"
    11  	"crypto/rsa"
    12  	"encoding/hex"
    13  	"encoding/pem"
    14  	"errors"
    15  	"fmt"
    16  	"io"
    17  	"math/big"
    18  	"net"
    19  	"os"
    20  	"os/exec"
    21  	"path/filepath"
    22  	"strings"
    23  	"testing"
    24  	"time"
    25  )
    26  
    27  // zeroSource is an io.Reader that returns an unlimited number of zero bytes.
    28  type zeroSource struct{}
    29  
    30  func (zeroSource) Read(b []byte) (n int, err error) {
    31  	for i := range b {
    32  		b[i] = 0
    33  	}
    34  
    35  	return len(b), nil
    36  }
    37  
    38  var testConfig *Config
    39  
    40  func allCipherSuites() []uint16 {
    41  	ids := make([]uint16, len(cipherSuites))
    42  	for i, suite := range cipherSuites {
    43  		ids[i] = suite.id
    44  	}
    45  
    46  	return ids
    47  }
    48  
    49  func init() {
    50  	testConfig = &Config{
    51  		Time:               func() time.Time { return time.Unix(0, 0) },
    52  		Rand:               zeroSource{},
    53  		Certificates:       make([]Certificate, 2),
    54  		InsecureSkipVerify: true,
    55  		MinVersion:         VersionSSL30,
    56  		MaxVersion:         VersionTLS12,
    57  		CipherSuites:       allCipherSuites(),
    58  	}
    59  	testConfig.Certificates[0].Certificate = [][]byte{testRSACertificate}
    60  	testConfig.Certificates[0].PrivateKey = testRSAPrivateKey
    61  	testConfig.Certificates[1].Certificate = [][]byte{testSNICertificate}
    62  	testConfig.Certificates[1].PrivateKey = testRSAPrivateKey
    63  	testConfig.BuildNameToCertificate()
    64  }
    65  
    66  func testClientHello(t *testing.T, serverConfig *Config, m handshakeMessage) {
    67  	testClientHelloFailure(t, serverConfig, m, "")
    68  }
    69  
    70  func testClientHelloFailure(t *testing.T, serverConfig *Config, m handshakeMessage, expectedSubStr string) {
    71  	// Create in-memory network connection,
    72  	// send message to server. Should return
    73  	// expected error.
    74  	c, s := net.Pipe()
    75  	go func() {
    76  		cli := Client(c, testConfig)
    77  		if ch, ok := m.(*clientHelloMsg); ok {
    78  			cli.vers = ch.vers
    79  		}
    80  		cli.writeRecord(recordTypeHandshake, m.marshal())
    81  		c.Close()
    82  	}()
    83  	hs := serverHandshakeState{
    84  		c: Server(s, serverConfig),
    85  	}
    86  	_, err := hs.readClientHello()
    87  	s.Close()
    88  	if len(expectedSubStr) == 0 {
    89  		if err != nil && err != io.EOF {
    90  			t.Errorf("Got error: %s; expected to succeed", err)
    91  		}
    92  	} else if err == nil || !strings.Contains(err.Error(), expectedSubStr) {
    93  		t.Errorf("Got error: %s; expected to match substring '%s'", err, expectedSubStr)
    94  	}
    95  }
    96  
    97  func TestSimpleError(t *testing.T) {
    98  	testClientHelloFailure(t, testConfig, &serverHelloDoneMsg{}, "unexpected handshake message")
    99  }
   100  
   101  var badProtocolVersions = []uint16{0x0000, 0x0005, 0x0100, 0x0105, 0x0200, 0x0205}
   102  
   103  func TestRejectBadProtocolVersion(t *testing.T) {
   104  	for _, v := range badProtocolVersions {
   105  		testClientHelloFailure(t, testConfig, &clientHelloMsg{vers: v}, "unsupported, maximum protocol version")
   106  	}
   107  }
   108  
   109  func TestNoSuiteOverlap(t *testing.T) {
   110  	clientHello := &clientHelloMsg{
   111  		vers:               VersionTLS10,
   112  		cipherSuites:       []uint16{0xff00},
   113  		compressionMethods: []uint8{compressionNone},
   114  	}
   115  	testClientHelloFailure(t, testConfig, clientHello, "no cipher suite supported by both client and server")
   116  }
   117  
   118  func TestNoCompressionOverlap(t *testing.T) {
   119  	clientHello := &clientHelloMsg{
   120  		vers:               VersionTLS10,
   121  		cipherSuites:       []uint16{TLS_RSA_WITH_RC4_128_SHA},
   122  		compressionMethods: []uint8{0xff},
   123  	}
   124  	testClientHelloFailure(t, testConfig, clientHello, "client does not support uncompressed connections")
   125  }
   126  
   127  func TestNoRC4ByDefault(t *testing.T) {
   128  	clientHello := &clientHelloMsg{
   129  		vers:               VersionTLS10,
   130  		cipherSuites:       []uint16{TLS_RSA_WITH_RC4_128_SHA},
   131  		compressionMethods: []uint8{compressionNone},
   132  	}
   133  	serverConfig := testConfig.Clone()
   134  	// Reset the enabled cipher suites to nil in order to test the
   135  	// defaults.
   136  	serverConfig.CipherSuites = nil
   137  	testClientHelloFailure(t, serverConfig, clientHello, "no cipher suite supported by both client and server")
   138  }
   139  
   140  func TestRejectSNIWithTrailingDot(t *testing.T) {
   141  	testClientHelloFailure(t, testConfig, &clientHelloMsg{vers: VersionTLS12, serverName: "foo.com."}, "unexpected message")
   142  }
   143  
   144  func TestDontSelectECDSAWithRSAKey(t *testing.T) {
   145  	// Test that, even when both sides support an ECDSA cipher suite, it
   146  	// won't be selected if the server's private key doesn't support it.
   147  	clientHello := &clientHelloMsg{
   148  		vers:               VersionTLS10,
   149  		cipherSuites:       []uint16{TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA},
   150  		compressionMethods: []uint8{compressionNone},
   151  		supportedCurves:    []CurveID{CurveP256},
   152  		supportedPoints:    []uint8{pointFormatUncompressed},
   153  	}
   154  	serverConfig := testConfig.Clone()
   155  	serverConfig.CipherSuites = clientHello.cipherSuites
   156  	serverConfig.Certificates = make([]Certificate, 1)
   157  	serverConfig.Certificates[0].Certificate = [][]byte{testECDSACertificate}
   158  	serverConfig.Certificates[0].PrivateKey = testECDSAPrivateKey
   159  	serverConfig.BuildNameToCertificate()
   160  	// First test that it *does* work when the server's key is ECDSA.
   161  	testClientHello(t, serverConfig, clientHello)
   162  
   163  	// Now test that switching to an RSA key causes the expected error (and
   164  	// not an internal error about a signing failure).
   165  	serverConfig.Certificates = testConfig.Certificates
   166  	testClientHelloFailure(t, serverConfig, clientHello, "no cipher suite supported by both client and server")
   167  }
   168  
   169  func TestDontSelectRSAWithECDSAKey(t *testing.T) {
   170  	// Test that, even when both sides support an RSA cipher suite, it
   171  	// won't be selected if the server's private key doesn't support it.
   172  	clientHello := &clientHelloMsg{
   173  		vers:               VersionTLS10,
   174  		cipherSuites:       []uint16{TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA},
   175  		compressionMethods: []uint8{compressionNone},
   176  		supportedCurves:    []CurveID{CurveP256},
   177  		supportedPoints:    []uint8{pointFormatUncompressed},
   178  	}
   179  	serverConfig := testConfig.Clone()
   180  	serverConfig.CipherSuites = clientHello.cipherSuites
   181  	// First test that it *does* work when the server's key is RSA.
   182  	testClientHello(t, serverConfig, clientHello)
   183  
   184  	// Now test that switching to an ECDSA key causes the expected error
   185  	// (and not an internal error about a signing failure).
   186  	serverConfig.Certificates = make([]Certificate, 1)
   187  	serverConfig.Certificates[0].Certificate = [][]byte{testECDSACertificate}
   188  	serverConfig.Certificates[0].PrivateKey = testECDSAPrivateKey
   189  	serverConfig.BuildNameToCertificate()
   190  	testClientHelloFailure(t, serverConfig, clientHello, "no cipher suite supported by both client and server")
   191  }
   192  
   193  func TestRenegotiationExtension(t *testing.T) {
   194  	clientHello := &clientHelloMsg{
   195  		vers:               VersionTLS12,
   196  		compressionMethods: []uint8{compressionNone},
   197  		random:             make([]byte, 32),
   198  		secureRenegotiationSupported: true,
   199  		cipherSuites:                 []uint16{TLS_RSA_WITH_RC4_128_SHA},
   200  	}
   201  
   202  	var buf []byte
   203  	c, s := net.Pipe()
   204  
   205  	go func() {
   206  		cli := Client(c, testConfig)
   207  		cli.vers = clientHello.vers
   208  		cli.writeRecord(recordTypeHandshake, clientHello.marshal())
   209  
   210  		buf = make([]byte, 1024)
   211  		n, err := c.Read(buf)
   212  		if err != nil {
   213  			t.Errorf("Server read returned error: %s", err)
   214  			return
   215  		}
   216  		buf = buf[:n]
   217  		c.Close()
   218  	}()
   219  
   220  	Server(s, testConfig).Handshake()
   221  
   222  	if len(buf) < 5+4 {
   223  		t.Fatalf("Server returned short message of length %d", len(buf))
   224  	}
   225  	// buf contains a TLS record, with a 5 byte record header and a 4 byte
   226  	// handshake header. The length of the ServerHello is taken from the
   227  	// handshake header.
   228  	serverHelloLen := int(buf[6])<<16 | int(buf[7])<<8 | int(buf[8])
   229  
   230  	var serverHello serverHelloMsg
   231  	// unmarshal expects to be given the handshake header, but
   232  	// serverHelloLen doesn't include it.
   233  	if !serverHello.unmarshal(buf[5 : 9+serverHelloLen]) {
   234  		t.Fatalf("Failed to parse ServerHello")
   235  	}
   236  
   237  	if !serverHello.secureRenegotiationSupported {
   238  		t.Errorf("Secure renegotiation extension was not echoed.")
   239  	}
   240  }
   241  
   242  func TestTLS12OnlyCipherSuites(t *testing.T) {
   243  	// Test that a Server doesn't select a TLS 1.2-only cipher suite when
   244  	// the client negotiates TLS 1.1.
   245  	var zeros [32]byte
   246  
   247  	clientHello := &clientHelloMsg{
   248  		vers:   VersionTLS11,
   249  		random: zeros[:],
   250  		cipherSuites: []uint16{
   251  			// The Server, by default, will use the client's
   252  			// preference order. So the GCM cipher suite
   253  			// will be selected unless it's excluded because
   254  			// of the version in this ClientHello.
   255  			TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
   256  			TLS_RSA_WITH_RC4_128_SHA,
   257  		},
   258  		compressionMethods: []uint8{compressionNone},
   259  		supportedCurves:    []CurveID{CurveP256, CurveP384, CurveP521},
   260  		supportedPoints:    []uint8{pointFormatUncompressed},
   261  	}
   262  
   263  	c, s := net.Pipe()
   264  	var reply interface{}
   265  	var clientErr error
   266  	go func() {
   267  		cli := Client(c, testConfig)
   268  		cli.vers = clientHello.vers
   269  		cli.writeRecord(recordTypeHandshake, clientHello.marshal())
   270  		reply, clientErr = cli.readHandshake()
   271  		c.Close()
   272  	}()
   273  	config := testConfig.Clone()
   274  	config.CipherSuites = clientHello.cipherSuites
   275  	Server(s, config).Handshake()
   276  	s.Close()
   277  	if clientErr != nil {
   278  		t.Fatal(clientErr)
   279  	}
   280  	serverHello, ok := reply.(*serverHelloMsg)
   281  	if !ok {
   282  		t.Fatalf("didn't get ServerHello message in reply. Got %v\n", reply)
   283  	}
   284  	if s := serverHello.cipherSuite; s != TLS_RSA_WITH_RC4_128_SHA {
   285  		t.Fatalf("bad cipher suite from server: %x", s)
   286  	}
   287  }
   288  
   289  func TestAlertForwarding(t *testing.T) {
   290  	c, s := net.Pipe()
   291  	go func() {
   292  		Client(c, testConfig).sendAlert(alertUnknownCA)
   293  		c.Close()
   294  	}()
   295  
   296  	err := Server(s, testConfig).Handshake()
   297  	s.Close()
   298  	if e, ok := err.(*net.OpError); !ok || e.Err != error(alertUnknownCA) {
   299  		t.Errorf("Got error: %s; expected: %s", err, error(alertUnknownCA))
   300  	}
   301  }
   302  
   303  func TestClose(t *testing.T) {
   304  	c, s := net.Pipe()
   305  	go c.Close()
   306  
   307  	err := Server(s, testConfig).Handshake()
   308  	s.Close()
   309  	if err != io.EOF {
   310  		t.Errorf("Got error: %s; expected: %s", err, io.EOF)
   311  	}
   312  }
   313  
   314  func testHandshake(clientConfig, serverConfig *Config) (serverState, clientState ConnectionState, err error) {
   315  	c, s := net.Pipe()
   316  	done := make(chan bool)
   317  	go func() {
   318  		cli := Client(c, clientConfig)
   319  		cli.Handshake()
   320  		clientState = cli.ConnectionState()
   321  		c.Close()
   322  		done <- true
   323  	}()
   324  	server := Server(s, serverConfig)
   325  	err = server.Handshake()
   326  	if err == nil {
   327  		serverState = server.ConnectionState()
   328  	}
   329  	s.Close()
   330  	<-done
   331  	return
   332  }
   333  
   334  func TestVersion(t *testing.T) {
   335  	serverConfig := &Config{
   336  		Certificates: testConfig.Certificates,
   337  		MaxVersion:   VersionTLS11,
   338  	}
   339  	clientConfig := &Config{
   340  		InsecureSkipVerify: true,
   341  	}
   342  	state, _, err := testHandshake(clientConfig, serverConfig)
   343  	if err != nil {
   344  		t.Fatalf("handshake failed: %s", err)
   345  	}
   346  	if state.Version != VersionTLS11 {
   347  		t.Fatalf("Incorrect version %x, should be %x", state.Version, VersionTLS11)
   348  	}
   349  }
   350  
   351  func TestCipherSuitePreference(t *testing.T) {
   352  	serverConfig := &Config{
   353  		CipherSuites: []uint16{TLS_RSA_WITH_RC4_128_SHA, TLS_RSA_WITH_AES_128_CBC_SHA, TLS_ECDHE_RSA_WITH_RC4_128_SHA},
   354  		Certificates: testConfig.Certificates,
   355  		MaxVersion:   VersionTLS11,
   356  	}
   357  	clientConfig := &Config{
   358  		CipherSuites:       []uint16{TLS_RSA_WITH_AES_128_CBC_SHA, TLS_RSA_WITH_RC4_128_SHA},
   359  		InsecureSkipVerify: true,
   360  	}
   361  	state, _, err := testHandshake(clientConfig, serverConfig)
   362  	if err != nil {
   363  		t.Fatalf("handshake failed: %s", err)
   364  	}
   365  	if state.CipherSuite != TLS_RSA_WITH_AES_128_CBC_SHA {
   366  		// By default the server should use the client's preference.
   367  		t.Fatalf("Client's preference was not used, got %x", state.CipherSuite)
   368  	}
   369  
   370  	serverConfig.PreferServerCipherSuites = true
   371  	state, _, err = testHandshake(clientConfig, serverConfig)
   372  	if err != nil {
   373  		t.Fatalf("handshake failed: %s", err)
   374  	}
   375  	if state.CipherSuite != TLS_RSA_WITH_RC4_128_SHA {
   376  		t.Fatalf("Server's preference was not used, got %x", state.CipherSuite)
   377  	}
   378  }
   379  
   380  func TestSCTHandshake(t *testing.T) {
   381  	expected := [][]byte{[]byte("certificate"), []byte("transparency")}
   382  	serverConfig := &Config{
   383  		Certificates: []Certificate{{
   384  			Certificate:                 [][]byte{testRSACertificate},
   385  			PrivateKey:                  testRSAPrivateKey,
   386  			SignedCertificateTimestamps: expected,
   387  		}},
   388  	}
   389  	clientConfig := &Config{
   390  		InsecureSkipVerify: true,
   391  	}
   392  	_, state, err := testHandshake(clientConfig, serverConfig)
   393  	if err != nil {
   394  		t.Fatalf("handshake failed: %s", err)
   395  	}
   396  	actual := state.SignedCertificateTimestamps
   397  	if len(actual) != len(expected) {
   398  		t.Fatalf("got %d scts, want %d", len(actual), len(expected))
   399  	}
   400  	for i, sct := range expected {
   401  		if !bytes.Equal(sct, actual[i]) {
   402  			t.Fatalf("SCT #%d was %x, but expected %x", i, actual[i], sct)
   403  		}
   404  	}
   405  }
   406  
   407  func TestCrossVersionResume(t *testing.T) {
   408  	serverConfig := &Config{
   409  		CipherSuites: []uint16{TLS_RSA_WITH_AES_128_CBC_SHA},
   410  		Certificates: testConfig.Certificates,
   411  	}
   412  	clientConfig := &Config{
   413  		CipherSuites:       []uint16{TLS_RSA_WITH_AES_128_CBC_SHA},
   414  		InsecureSkipVerify: true,
   415  		ClientSessionCache: NewLRUClientSessionCache(1),
   416  		ServerName:         "servername",
   417  	}
   418  
   419  	// Establish a session at TLS 1.1.
   420  	clientConfig.MaxVersion = VersionTLS11
   421  	_, _, err := testHandshake(clientConfig, serverConfig)
   422  	if err != nil {
   423  		t.Fatalf("handshake failed: %s", err)
   424  	}
   425  
   426  	// The client session cache now contains a TLS 1.1 session.
   427  	state, _, err := testHandshake(clientConfig, serverConfig)
   428  	if err != nil {
   429  		t.Fatalf("handshake failed: %s", err)
   430  	}
   431  	if !state.DidResume {
   432  		t.Fatalf("handshake did not resume at the same version")
   433  	}
   434  
   435  	// Test that the server will decline to resume at a lower version.
   436  	clientConfig.MaxVersion = VersionTLS10
   437  	state, _, err = testHandshake(clientConfig, serverConfig)
   438  	if err != nil {
   439  		t.Fatalf("handshake failed: %s", err)
   440  	}
   441  	if state.DidResume {
   442  		t.Fatalf("handshake resumed at a lower version")
   443  	}
   444  
   445  	// The client session cache now contains a TLS 1.0 session.
   446  	state, _, err = testHandshake(clientConfig, serverConfig)
   447  	if err != nil {
   448  		t.Fatalf("handshake failed: %s", err)
   449  	}
   450  	if !state.DidResume {
   451  		t.Fatalf("handshake did not resume at the same version")
   452  	}
   453  
   454  	// Test that the server will decline to resume at a higher version.
   455  	clientConfig.MaxVersion = VersionTLS11
   456  	state, _, err = testHandshake(clientConfig, serverConfig)
   457  	if err != nil {
   458  		t.Fatalf("handshake failed: %s", err)
   459  	}
   460  	if state.DidResume {
   461  		t.Fatalf("handshake resumed at a higher version")
   462  	}
   463  }
   464  
   465  // Note: see comment in handshake_test.go for details of how the reference
   466  // tests work.
   467  
   468  // serverTest represents a test of the TLS server handshake against a reference
   469  // implementation.
   470  type serverTest struct {
   471  	// name is a freeform string identifying the test and the file in which
   472  	// the expected results will be stored.
   473  	name string
   474  	// command, if not empty, contains a series of arguments for the
   475  	// command to run for the reference server.
   476  	command []string
   477  	// expectedPeerCerts contains a list of PEM blocks of expected
   478  	// certificates from the client.
   479  	expectedPeerCerts []string
   480  	// config, if not nil, contains a custom Config to use for this test.
   481  	config *Config
   482  	// expectHandshakeErrorIncluding, when not empty, contains a string
   483  	// that must be a substring of the error resulting from the handshake.
   484  	expectHandshakeErrorIncluding string
   485  	// validate, if not nil, is a function that will be called with the
   486  	// ConnectionState of the resulting connection. It returns false if the
   487  	// ConnectionState is unacceptable.
   488  	validate func(ConnectionState) error
   489  }
   490  
   491  var defaultClientCommand = []string{"openssl", "s_client", "-no_ticket"}
   492  
   493  // connFromCommand starts opens a listening socket and starts the reference
   494  // client to connect to it. It returns a recordingConn that wraps the resulting
   495  // connection.
   496  func (test *serverTest) connFromCommand() (conn *recordingConn, child *exec.Cmd, err error) {
   497  	l, err := net.ListenTCP("tcp", &net.TCPAddr{
   498  		IP:   net.IPv4(127, 0, 0, 1),
   499  		Port: 0,
   500  	})
   501  	if err != nil {
   502  		return nil, nil, err
   503  	}
   504  	defer l.Close()
   505  
   506  	port := l.Addr().(*net.TCPAddr).Port
   507  
   508  	var command []string
   509  	command = append(command, test.command...)
   510  	if len(command) == 0 {
   511  		command = defaultClientCommand
   512  	}
   513  	command = append(command, "-connect")
   514  	command = append(command, fmt.Sprintf("127.0.0.1:%d", port))
   515  	cmd := exec.Command(command[0], command[1:]...)
   516  	cmd.Stdin = nil
   517  	var output bytes.Buffer
   518  	cmd.Stdout = &output
   519  	cmd.Stderr = &output
   520  	if err := cmd.Start(); err != nil {
   521  		return nil, nil, err
   522  	}
   523  
   524  	connChan := make(chan interface{})
   525  	go func() {
   526  		tcpConn, err := l.Accept()
   527  		if err != nil {
   528  			connChan <- err
   529  		}
   530  		connChan <- tcpConn
   531  	}()
   532  
   533  	var tcpConn net.Conn
   534  	select {
   535  	case connOrError := <-connChan:
   536  		if err, ok := connOrError.(error); ok {
   537  			return nil, nil, err
   538  		}
   539  		tcpConn = connOrError.(net.Conn)
   540  	case <-time.After(2 * time.Second):
   541  		output.WriteTo(os.Stdout)
   542  		return nil, nil, errors.New("timed out waiting for connection from child process")
   543  	}
   544  
   545  	record := &recordingConn{
   546  		Conn: tcpConn,
   547  	}
   548  
   549  	return record, cmd, nil
   550  }
   551  
   552  func (test *serverTest) dataPath() string {
   553  	return filepath.Join("testdata", "Server-"+test.name)
   554  }
   555  
   556  func (test *serverTest) loadData() (flows [][]byte, err error) {
   557  	in, err := os.Open(test.dataPath())
   558  	if err != nil {
   559  		return nil, err
   560  	}
   561  	defer in.Close()
   562  	return parseTestData(in)
   563  }
   564  
   565  func (test *serverTest) run(t *testing.T, write bool) {
   566  	checkOpenSSLVersion(t)
   567  
   568  	var clientConn, serverConn net.Conn
   569  	var recordingConn *recordingConn
   570  	var childProcess *exec.Cmd
   571  
   572  	if write {
   573  		var err error
   574  		recordingConn, childProcess, err = test.connFromCommand()
   575  		if err != nil {
   576  			t.Fatalf("Failed to start subcommand: %s", err)
   577  		}
   578  		serverConn = recordingConn
   579  	} else {
   580  		clientConn, serverConn = net.Pipe()
   581  	}
   582  	config := test.config
   583  	if config == nil {
   584  		config = testConfig
   585  	}
   586  	server := Server(serverConn, config)
   587  	connStateChan := make(chan ConnectionState, 1)
   588  	go func() {
   589  		_, err := server.Write([]byte("hello, world\n"))
   590  		if len(test.expectHandshakeErrorIncluding) > 0 {
   591  			if err == nil {
   592  				t.Errorf("Error expected, but no error returned")
   593  			} else if s := err.Error(); !strings.Contains(s, test.expectHandshakeErrorIncluding) {
   594  				t.Errorf("Error expected containing '%s' but got '%s'", test.expectHandshakeErrorIncluding, s)
   595  			}
   596  		} else {
   597  			if err != nil {
   598  				t.Logf("Error from Server.Write: '%s'", err)
   599  			}
   600  		}
   601  		server.Close()
   602  		serverConn.Close()
   603  		connStateChan <- server.ConnectionState()
   604  	}()
   605  
   606  	if !write {
   607  		flows, err := test.loadData()
   608  		if err != nil {
   609  			t.Fatalf("%s: failed to load data from %s", test.name, test.dataPath())
   610  		}
   611  		for i, b := range flows {
   612  			if i%2 == 0 {
   613  				clientConn.Write(b)
   614  				continue
   615  			}
   616  			bb := make([]byte, len(b))
   617  			n, err := io.ReadFull(clientConn, bb)
   618  			if err != nil {
   619  				t.Fatalf("%s #%d: %s\nRead %d, wanted %d, got %x, wanted %x\n", test.name, i+1, err, n, len(bb), bb[:n], b)
   620  			}
   621  			if !bytes.Equal(b, bb) {
   622  				t.Fatalf("%s #%d: mismatch on read: got:%x want:%x", test.name, i+1, bb, b)
   623  			}
   624  		}
   625  		clientConn.Close()
   626  	}
   627  
   628  	connState := <-connStateChan
   629  	peerCerts := connState.PeerCertificates
   630  	if len(peerCerts) == len(test.expectedPeerCerts) {
   631  		for i, peerCert := range peerCerts {
   632  			block, _ := pem.Decode([]byte(test.expectedPeerCerts[i]))
   633  			if !bytes.Equal(block.Bytes, peerCert.Raw) {
   634  				t.Fatalf("%s: mismatch on peer cert %d", test.name, i+1)
   635  			}
   636  		}
   637  	} else {
   638  		t.Fatalf("%s: mismatch on peer list length: %d (wanted) != %d (got)", test.name, len(test.expectedPeerCerts), len(peerCerts))
   639  	}
   640  
   641  	if test.validate != nil {
   642  		if err := test.validate(connState); err != nil {
   643  			t.Fatalf("validate callback returned error: %s", err)
   644  		}
   645  	}
   646  
   647  	if write {
   648  		path := test.dataPath()
   649  		out, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644)
   650  		if err != nil {
   651  			t.Fatalf("Failed to create output file: %s", err)
   652  		}
   653  		defer out.Close()
   654  		recordingConn.Close()
   655  		if len(recordingConn.flows) < 3 {
   656  			childProcess.Stdout.(*bytes.Buffer).WriteTo(os.Stdout)
   657  			if len(test.expectHandshakeErrorIncluding) == 0 {
   658  				t.Fatalf("Handshake failed")
   659  			}
   660  		}
   661  		recordingConn.WriteTo(out)
   662  		fmt.Printf("Wrote %s\n", path)
   663  		childProcess.Wait()
   664  	}
   665  }
   666  
   667  func runServerTestForVersion(t *testing.T, template *serverTest, prefix, option string) {
   668  	setParallel(t)
   669  	test := *template
   670  	test.name = prefix + test.name
   671  	if len(test.command) == 0 {
   672  		test.command = defaultClientCommand
   673  	}
   674  	test.command = append([]string(nil), test.command...)
   675  	test.command = append(test.command, option)
   676  	test.run(t, *update)
   677  }
   678  
   679  func runServerTestSSLv3(t *testing.T, template *serverTest) {
   680  	runServerTestForVersion(t, template, "SSLv3-", "-ssl3")
   681  }
   682  
   683  func runServerTestTLS10(t *testing.T, template *serverTest) {
   684  	runServerTestForVersion(t, template, "TLSv10-", "-tls1")
   685  }
   686  
   687  func runServerTestTLS11(t *testing.T, template *serverTest) {
   688  	runServerTestForVersion(t, template, "TLSv11-", "-tls1_1")
   689  }
   690  
   691  func runServerTestTLS12(t *testing.T, template *serverTest) {
   692  	runServerTestForVersion(t, template, "TLSv12-", "-tls1_2")
   693  }
   694  
   695  func TestHandshakeServerRSARC4(t *testing.T) {
   696  	test := &serverTest{
   697  		name:    "RSA-RC4",
   698  		command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "RC4-SHA"},
   699  	}
   700  	runServerTestSSLv3(t, test)
   701  	runServerTestTLS10(t, test)
   702  	runServerTestTLS11(t, test)
   703  	runServerTestTLS12(t, test)
   704  }
   705  
   706  func TestHandshakeServerRSA3DES(t *testing.T) {
   707  	test := &serverTest{
   708  		name:    "RSA-3DES",
   709  		command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "DES-CBC3-SHA"},
   710  	}
   711  	runServerTestSSLv3(t, test)
   712  	runServerTestTLS10(t, test)
   713  	runServerTestTLS12(t, test)
   714  }
   715  
   716  func TestHandshakeServerRSAAES(t *testing.T) {
   717  	test := &serverTest{
   718  		name:    "RSA-AES",
   719  		command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "AES128-SHA"},
   720  	}
   721  	runServerTestSSLv3(t, test)
   722  	runServerTestTLS10(t, test)
   723  	runServerTestTLS12(t, test)
   724  }
   725  
   726  func TestHandshakeServerAESGCM(t *testing.T) {
   727  	test := &serverTest{
   728  		name:    "RSA-AES-GCM",
   729  		command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "ECDHE-RSA-AES128-GCM-SHA256"},
   730  	}
   731  	runServerTestTLS12(t, test)
   732  }
   733  
   734  func TestHandshakeServerAES256GCMSHA384(t *testing.T) {
   735  	test := &serverTest{
   736  		name:    "RSA-AES256-GCM-SHA384",
   737  		command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "ECDHE-RSA-AES256-GCM-SHA384"},
   738  	}
   739  	runServerTestTLS12(t, test)
   740  }
   741  
   742  func TestHandshakeServerECDHEECDSAAES(t *testing.T) {
   743  	config := testConfig.Clone()
   744  	config.Certificates = make([]Certificate, 1)
   745  	config.Certificates[0].Certificate = [][]byte{testECDSACertificate}
   746  	config.Certificates[0].PrivateKey = testECDSAPrivateKey
   747  	config.BuildNameToCertificate()
   748  
   749  	test := &serverTest{
   750  		name:    "ECDHE-ECDSA-AES",
   751  		command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "ECDHE-ECDSA-AES256-SHA"},
   752  		config:  config,
   753  	}
   754  	runServerTestTLS10(t, test)
   755  	runServerTestTLS12(t, test)
   756  }
   757  
   758  func TestHandshakeServerX25519(t *testing.T) {
   759  	config := testConfig.Clone()
   760  	config.CurvePreferences = []CurveID{X25519}
   761  
   762  	test := &serverTest{
   763  		name:    "X25519-ECDHE-RSA-AES-GCM",
   764  		command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "ECDHE-RSA-AES128-GCM-SHA256"},
   765  		config:  config,
   766  	}
   767  	runServerTestTLS12(t, test)
   768  }
   769  
   770  func TestHandshakeServerALPN(t *testing.T) {
   771  	config := testConfig.Clone()
   772  	config.NextProtos = []string{"proto1", "proto2"}
   773  
   774  	test := &serverTest{
   775  		name: "ALPN",
   776  		// Note that this needs OpenSSL 1.0.2 because that is the first
   777  		// version that supports the -alpn flag.
   778  		command: []string{"openssl", "s_client", "-alpn", "proto2,proto1"},
   779  		config:  config,
   780  		validate: func(state ConnectionState) error {
   781  			// The server's preferences should override the client.
   782  			if state.NegotiatedProtocol != "proto1" {
   783  				return fmt.Errorf("Got protocol %q, wanted proto1", state.NegotiatedProtocol)
   784  			}
   785  			return nil
   786  		},
   787  	}
   788  	runServerTestTLS12(t, test)
   789  }
   790  
   791  func TestHandshakeServerALPNNoMatch(t *testing.T) {
   792  	config := testConfig.Clone()
   793  	config.NextProtos = []string{"proto3"}
   794  
   795  	test := &serverTest{
   796  		name: "ALPN-NoMatch",
   797  		// Note that this needs OpenSSL 1.0.2 because that is the first
   798  		// version that supports the -alpn flag.
   799  		command: []string{"openssl", "s_client", "-alpn", "proto2,proto1"},
   800  		config:  config,
   801  		validate: func(state ConnectionState) error {
   802  			// Rather than reject the connection, Go doesn't select
   803  			// a protocol when there is no overlap.
   804  			if state.NegotiatedProtocol != "" {
   805  				return fmt.Errorf("Got protocol %q, wanted ''", state.NegotiatedProtocol)
   806  			}
   807  			return nil
   808  		},
   809  	}
   810  	runServerTestTLS12(t, test)
   811  }
   812  
   813  // TestHandshakeServerSNI involves a client sending an SNI extension of
   814  // "snitest.com", which happens to match the CN of testSNICertificate. The test
   815  // verifies that the server correctly selects that certificate.
   816  func TestHandshakeServerSNI(t *testing.T) {
   817  	test := &serverTest{
   818  		name:    "SNI",
   819  		command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "AES128-SHA", "-servername", "snitest.com"},
   820  	}
   821  	runServerTestTLS12(t, test)
   822  }
   823  
   824  // TestHandshakeServerSNICertForName is similar to TestHandshakeServerSNI, but
   825  // tests the dynamic GetCertificate method
   826  func TestHandshakeServerSNIGetCertificate(t *testing.T) {
   827  	config := testConfig.Clone()
   828  
   829  	// Replace the NameToCertificate map with a GetCertificate function
   830  	nameToCert := config.NameToCertificate
   831  	config.NameToCertificate = nil
   832  	config.GetCertificate = func(clientHello *ClientHelloInfo) (*Certificate, error) {
   833  		cert, _ := nameToCert[clientHello.ServerName]
   834  		return cert, nil
   835  	}
   836  	test := &serverTest{
   837  		name:    "SNI-GetCertificate",
   838  		command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "AES128-SHA", "-servername", "snitest.com"},
   839  		config:  config,
   840  	}
   841  	runServerTestTLS12(t, test)
   842  }
   843  
   844  // TestHandshakeServerSNICertForNameNotFound is similar to
   845  // TestHandshakeServerSNICertForName, but tests to make sure that when the
   846  // GetCertificate method doesn't return a cert, we fall back to what's in
   847  // the NameToCertificate map.
   848  func TestHandshakeServerSNIGetCertificateNotFound(t *testing.T) {
   849  	config := testConfig.Clone()
   850  
   851  	config.GetCertificate = func(clientHello *ClientHelloInfo) (*Certificate, error) {
   852  		return nil, nil
   853  	}
   854  	test := &serverTest{
   855  		name:    "SNI-GetCertificateNotFound",
   856  		command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "AES128-SHA", "-servername", "snitest.com"},
   857  		config:  config,
   858  	}
   859  	runServerTestTLS12(t, test)
   860  }
   861  
   862  // TestHandshakeServerSNICertForNameError tests to make sure that errors in
   863  // GetCertificate result in a tls alert.
   864  func TestHandshakeServerSNIGetCertificateError(t *testing.T) {
   865  	const errMsg = "TestHandshakeServerSNIGetCertificateError error"
   866  
   867  	serverConfig := testConfig.Clone()
   868  	serverConfig.GetCertificate = func(clientHello *ClientHelloInfo) (*Certificate, error) {
   869  		return nil, errors.New(errMsg)
   870  	}
   871  
   872  	clientHello := &clientHelloMsg{
   873  		vers:               VersionTLS10,
   874  		cipherSuites:       []uint16{TLS_RSA_WITH_RC4_128_SHA},
   875  		compressionMethods: []uint8{compressionNone},
   876  		serverName:         "test",
   877  	}
   878  	testClientHelloFailure(t, serverConfig, clientHello, errMsg)
   879  }
   880  
   881  // TestHandshakeServerEmptyCertificates tests that GetCertificates is called in
   882  // the case that Certificates is empty, even without SNI.
   883  func TestHandshakeServerEmptyCertificates(t *testing.T) {
   884  	const errMsg = "TestHandshakeServerEmptyCertificates error"
   885  
   886  	serverConfig := testConfig.Clone()
   887  	serverConfig.GetCertificate = func(clientHello *ClientHelloInfo) (*Certificate, error) {
   888  		return nil, errors.New(errMsg)
   889  	}
   890  	serverConfig.Certificates = nil
   891  
   892  	clientHello := &clientHelloMsg{
   893  		vers:               VersionTLS10,
   894  		cipherSuites:       []uint16{TLS_RSA_WITH_RC4_128_SHA},
   895  		compressionMethods: []uint8{compressionNone},
   896  	}
   897  	testClientHelloFailure(t, serverConfig, clientHello, errMsg)
   898  
   899  	// With an empty Certificates and a nil GetCertificate, the server
   900  	// should always return a “no certificates” error.
   901  	serverConfig.GetCertificate = nil
   902  
   903  	clientHello = &clientHelloMsg{
   904  		vers:               VersionTLS10,
   905  		cipherSuites:       []uint16{TLS_RSA_WITH_RC4_128_SHA},
   906  		compressionMethods: []uint8{compressionNone},
   907  	}
   908  	testClientHelloFailure(t, serverConfig, clientHello, "no certificates")
   909  }
   910  
   911  // TestCipherSuiteCertPreferance ensures that we select an RSA ciphersuite with
   912  // an RSA certificate and an ECDSA ciphersuite with an ECDSA certificate.
   913  func TestCipherSuiteCertPreferenceECDSA(t *testing.T) {
   914  	config := testConfig.Clone()
   915  	config.CipherSuites = []uint16{TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA}
   916  	config.PreferServerCipherSuites = true
   917  
   918  	test := &serverTest{
   919  		name:   "CipherSuiteCertPreferenceRSA",
   920  		config: config,
   921  	}
   922  	runServerTestTLS12(t, test)
   923  
   924  	config = testConfig.Clone()
   925  	config.CipherSuites = []uint16{TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA, TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA}
   926  	config.Certificates = []Certificate{
   927  		{
   928  			Certificate: [][]byte{testECDSACertificate},
   929  			PrivateKey:  testECDSAPrivateKey,
   930  		},
   931  	}
   932  	config.BuildNameToCertificate()
   933  	config.PreferServerCipherSuites = true
   934  
   935  	test = &serverTest{
   936  		name:   "CipherSuiteCertPreferenceECDSA",
   937  		config: config,
   938  	}
   939  	runServerTestTLS12(t, test)
   940  }
   941  
   942  func TestResumption(t *testing.T) {
   943  	sessionFilePath := tempFile("")
   944  	defer os.Remove(sessionFilePath)
   945  
   946  	test := &serverTest{
   947  		name:    "IssueTicket",
   948  		command: []string{"openssl", "s_client", "-cipher", "AES128-SHA", "-sess_out", sessionFilePath},
   949  	}
   950  	runServerTestTLS12(t, test)
   951  
   952  	test = &serverTest{
   953  		name:    "Resume",
   954  		command: []string{"openssl", "s_client", "-cipher", "AES128-SHA", "-sess_in", sessionFilePath},
   955  	}
   956  	runServerTestTLS12(t, test)
   957  }
   958  
   959  func TestResumptionDisabled(t *testing.T) {
   960  	sessionFilePath := tempFile("")
   961  	defer os.Remove(sessionFilePath)
   962  
   963  	config := testConfig.Clone()
   964  
   965  	test := &serverTest{
   966  		name:    "IssueTicketPreDisable",
   967  		command: []string{"openssl", "s_client", "-cipher", "AES128-SHA", "-sess_out", sessionFilePath},
   968  		config:  config,
   969  	}
   970  	runServerTestTLS12(t, test)
   971  
   972  	config.SessionTicketsDisabled = true
   973  
   974  	test = &serverTest{
   975  		name:    "ResumeDisabled",
   976  		command: []string{"openssl", "s_client", "-cipher", "AES128-SHA", "-sess_in", sessionFilePath},
   977  		config:  config,
   978  	}
   979  	runServerTestTLS12(t, test)
   980  
   981  	// One needs to manually confirm that the handshake in the golden data
   982  	// file for ResumeDisabled does not include a resumption handshake.
   983  }
   984  
   985  func TestFallbackSCSV(t *testing.T) {
   986  	serverConfig := Config{
   987  		Certificates: testConfig.Certificates,
   988  	}
   989  	test := &serverTest{
   990  		name:   "FallbackSCSV",
   991  		config: &serverConfig,
   992  		// OpenSSL 1.0.1j is needed for the -fallback_scsv option.
   993  		command: []string{"openssl", "s_client", "-fallback_scsv"},
   994  		expectHandshakeErrorIncluding: "inappropriate protocol fallback",
   995  	}
   996  	runServerTestTLS11(t, test)
   997  }
   998  
   999  // clientCertificatePEM and clientKeyPEM were generated with generate_cert.go
  1000  // Thus, they have no ExtKeyUsage fields and trigger an error when verification
  1001  // is turned on.
  1002  
  1003  const clientCertificatePEM = `
  1004  -----BEGIN CERTIFICATE-----
  1005  MIIB7zCCAVigAwIBAgIQXBnBiWWDVW/cC8m5k5/pvDANBgkqhkiG9w0BAQsFADAS
  1006  MRAwDgYDVQQKEwdBY21lIENvMB4XDTE2MDgxNzIxNTIzMVoXDTE3MDgxNzIxNTIz
  1007  MVowEjEQMA4GA1UEChMHQWNtZSBDbzCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkC
  1008  gYEAum+qhr3Pv5/y71yUYHhv6BPy0ZZvzdkybiI3zkH5yl0prOEn2mGi7oHLEMff
  1009  NFiVhuk9GeZcJ3NgyI14AvQdpJgJoxlwaTwlYmYqqyIjxXuFOE8uCXMyp70+m63K
  1010  hAfmDzr/d8WdQYUAirab7rCkPy1MTOZCPrtRyN1IVPQMjkcCAwEAAaNGMEQwDgYD
  1011  VR0PAQH/BAQDAgWgMBMGA1UdJQQMMAoGCCsGAQUFBwMBMAwGA1UdEwEB/wQCMAAw
  1012  DwYDVR0RBAgwBocEfwAAATANBgkqhkiG9w0BAQsFAAOBgQBGq0Si+yhU+Fpn+GKU
  1013  8ZqyGJ7ysd4dfm92lam6512oFmyc9wnTN+RLKzZ8Aa1B0jLYw9KT+RBrjpW5LBeK
  1014  o0RIvFkTgxYEiKSBXCUNmAysEbEoVr4dzWFihAm/1oDGRY2CLLTYg5vbySK3KhIR
  1015  e/oCO8HJ/+rJnahJ05XX1Q7lNQ==
  1016  -----END CERTIFICATE-----`
  1017  
  1018  const clientKeyPEM = `
  1019  -----BEGIN RSA PRIVATE KEY-----
  1020  MIICXQIBAAKBgQC6b6qGvc+/n/LvXJRgeG/oE/LRlm/N2TJuIjfOQfnKXSms4Sfa
  1021  YaLugcsQx980WJWG6T0Z5lwnc2DIjXgC9B2kmAmjGXBpPCViZiqrIiPFe4U4Ty4J
  1022  czKnvT6brcqEB+YPOv93xZ1BhQCKtpvusKQ/LUxM5kI+u1HI3UhU9AyORwIDAQAB
  1023  AoGAEJZ03q4uuMb7b26WSQsOMeDsftdatT747LGgs3pNRkMJvTb/O7/qJjxoG+Mc
  1024  qeSj0TAZXp+PXXc3ikCECAc+R8rVMfWdmp903XgO/qYtmZGCorxAHEmR80SrfMXv
  1025  PJnznLQWc8U9nphQErR+tTESg7xWEzmFcPKwnZd1xg8ERYkCQQDTGtrFczlB2b/Z
  1026  9TjNMqUlMnTLIk/a/rPE2fLLmAYhK5sHnJdvDURaH2mF4nso0EGtENnTsh6LATnY
  1027  dkrxXGm9AkEA4hXHG2q3MnhgK1Z5hjv+Fnqd+8bcbII9WW4flFs15EKoMgS1w/PJ
  1028  zbsySaSy5IVS8XeShmT9+3lrleed4sy+UwJBAJOOAbxhfXP5r4+5R6ql66jES75w
  1029  jUCVJzJA5ORJrn8g64u2eGK28z/LFQbv9wXgCwfc72R468BdawFSLa/m2EECQGbZ
  1030  rWiFla26IVXV0xcD98VWJsTBZMlgPnSOqoMdM1kSEd4fUmlAYI/dFzV1XYSkOmVr
  1031  FhdZnklmpVDeu27P4c0CQQCuCOup0FlJSBpWY1TTfun/KMBkBatMz0VMA3d7FKIU
  1032  csPezl677Yjo8u1r/KzeI6zLg87Z8E6r6ZWNc9wBSZK6
  1033  -----END RSA PRIVATE KEY-----`
  1034  
  1035  const clientECDSACertificatePEM = `
  1036  -----BEGIN CERTIFICATE-----
  1037  MIIB/DCCAV4CCQCaMIRsJjXZFzAJBgcqhkjOPQQBMEUxCzAJBgNVBAYTAkFVMRMw
  1038  EQYDVQQIEwpTb21lLVN0YXRlMSEwHwYDVQQKExhJbnRlcm5ldCBXaWRnaXRzIFB0
  1039  eSBMdGQwHhcNMTIxMTE0MTMyNTUzWhcNMjIxMTEyMTMyNTUzWjBBMQswCQYDVQQG
  1040  EwJBVTEMMAoGA1UECBMDTlNXMRAwDgYDVQQHEwdQeXJtb250MRIwEAYDVQQDEwlK
  1041  b2VsIFNpbmcwgZswEAYHKoZIzj0CAQYFK4EEACMDgYYABACVjJF1FMBexFe01MNv
  1042  ja5oHt1vzobhfm6ySD6B5U7ixohLZNz1MLvT/2XMW/TdtWo+PtAd3kfDdq0Z9kUs
  1043  jLzYHQFMH3CQRnZIi4+DzEpcj0B22uCJ7B0rxE4wdihBsmKo+1vx+U56jb0JuK7q
  1044  ixgnTy5w/hOWusPTQBbNZU6sER7m8TAJBgcqhkjOPQQBA4GMADCBiAJCAOAUxGBg
  1045  C3JosDJdYUoCdFzCgbkWqD8pyDbHgf9stlvZcPE4O1BIKJTLCRpS8V3ujfK58PDa
  1046  2RU6+b0DeoeiIzXsAkIBo9SKeDUcSpoj0gq+KxAxnZxfvuiRs9oa9V2jI/Umi0Vw
  1047  jWVim34BmT0Y9hCaOGGbLlfk+syxis7iI6CH8OFnUes=
  1048  -----END CERTIFICATE-----`
  1049  
  1050  const clientECDSAKeyPEM = `
  1051  -----BEGIN EC PARAMETERS-----
  1052  BgUrgQQAIw==
  1053  -----END EC PARAMETERS-----
  1054  -----BEGIN EC PRIVATE KEY-----
  1055  MIHcAgEBBEIBkJN9X4IqZIguiEVKMqeBUP5xtRsEv4HJEtOpOGLELwO53SD78Ew8
  1056  k+wLWoqizS3NpQyMtrU8JFdWfj+C57UNkOugBwYFK4EEACOhgYkDgYYABACVjJF1
  1057  FMBexFe01MNvja5oHt1vzobhfm6ySD6B5U7ixohLZNz1MLvT/2XMW/TdtWo+PtAd
  1058  3kfDdq0Z9kUsjLzYHQFMH3CQRnZIi4+DzEpcj0B22uCJ7B0rxE4wdihBsmKo+1vx
  1059  +U56jb0JuK7qixgnTy5w/hOWusPTQBbNZU6sER7m8Q==
  1060  -----END EC PRIVATE KEY-----`
  1061  
  1062  func TestClientAuth(t *testing.T) {
  1063  	setParallel(t)
  1064  	var certPath, keyPath, ecdsaCertPath, ecdsaKeyPath string
  1065  
  1066  	if *update {
  1067  		certPath = tempFile(clientCertificatePEM)
  1068  		defer os.Remove(certPath)
  1069  		keyPath = tempFile(clientKeyPEM)
  1070  		defer os.Remove(keyPath)
  1071  		ecdsaCertPath = tempFile(clientECDSACertificatePEM)
  1072  		defer os.Remove(ecdsaCertPath)
  1073  		ecdsaKeyPath = tempFile(clientECDSAKeyPEM)
  1074  		defer os.Remove(ecdsaKeyPath)
  1075  	}
  1076  
  1077  	config := testConfig.Clone()
  1078  	config.ClientAuth = RequestClientCert
  1079  
  1080  	test := &serverTest{
  1081  		name:    "ClientAuthRequestedNotGiven",
  1082  		command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "AES128-SHA"},
  1083  		config:  config,
  1084  	}
  1085  	runServerTestTLS12(t, test)
  1086  
  1087  	test = &serverTest{
  1088  		name:              "ClientAuthRequestedAndGiven",
  1089  		command:           []string{"openssl", "s_client", "-no_ticket", "-cipher", "AES128-SHA", "-cert", certPath, "-key", keyPath},
  1090  		config:            config,
  1091  		expectedPeerCerts: []string{clientCertificatePEM},
  1092  	}
  1093  	runServerTestTLS12(t, test)
  1094  
  1095  	test = &serverTest{
  1096  		name:              "ClientAuthRequestedAndECDSAGiven",
  1097  		command:           []string{"openssl", "s_client", "-no_ticket", "-cipher", "AES128-SHA", "-cert", ecdsaCertPath, "-key", ecdsaKeyPath},
  1098  		config:            config,
  1099  		expectedPeerCerts: []string{clientECDSACertificatePEM},
  1100  	}
  1101  	runServerTestTLS12(t, test)
  1102  }
  1103  
  1104  func TestSNIGivenOnFailure(t *testing.T) {
  1105  	const expectedServerName = "test.testing"
  1106  
  1107  	clientHello := &clientHelloMsg{
  1108  		vers:               VersionTLS10,
  1109  		cipherSuites:       []uint16{TLS_RSA_WITH_RC4_128_SHA},
  1110  		compressionMethods: []uint8{compressionNone},
  1111  		serverName:         expectedServerName,
  1112  	}
  1113  
  1114  	serverConfig := testConfig.Clone()
  1115  	// Erase the server's cipher suites to ensure the handshake fails.
  1116  	serverConfig.CipherSuites = nil
  1117  
  1118  	c, s := net.Pipe()
  1119  	go func() {
  1120  		cli := Client(c, testConfig)
  1121  		cli.vers = clientHello.vers
  1122  		cli.writeRecord(recordTypeHandshake, clientHello.marshal())
  1123  		c.Close()
  1124  	}()
  1125  	hs := serverHandshakeState{
  1126  		c: Server(s, serverConfig),
  1127  	}
  1128  	_, err := hs.readClientHello()
  1129  	defer s.Close()
  1130  
  1131  	if err == nil {
  1132  		t.Error("No error reported from server")
  1133  	}
  1134  
  1135  	cs := hs.c.ConnectionState()
  1136  	if cs.HandshakeComplete {
  1137  		t.Error("Handshake registered as complete")
  1138  	}
  1139  
  1140  	if cs.ServerName != expectedServerName {
  1141  		t.Errorf("Expected ServerName of %q, but got %q", expectedServerName, cs.ServerName)
  1142  	}
  1143  }
  1144  
  1145  var getConfigForClientTests = []struct {
  1146  	setup          func(config *Config)
  1147  	callback       func(clientHello *ClientHelloInfo) (*Config, error)
  1148  	errorSubstring string
  1149  	verify         func(config *Config) error
  1150  }{
  1151  	{
  1152  		nil,
  1153  		func(clientHello *ClientHelloInfo) (*Config, error) {
  1154  			return nil, nil
  1155  		},
  1156  		"",
  1157  		nil,
  1158  	},
  1159  	{
  1160  		nil,
  1161  		func(clientHello *ClientHelloInfo) (*Config, error) {
  1162  			return nil, errors.New("should bubble up")
  1163  		},
  1164  		"should bubble up",
  1165  		nil,
  1166  	},
  1167  	{
  1168  		nil,
  1169  		func(clientHello *ClientHelloInfo) (*Config, error) {
  1170  			config := testConfig.Clone()
  1171  			// Setting a maximum version of TLS 1.1 should cause
  1172  			// the handshake to fail.
  1173  			config.MaxVersion = VersionTLS11
  1174  			return config, nil
  1175  		},
  1176  		"version 301 when expecting version 302",
  1177  		nil,
  1178  	},
  1179  	{
  1180  		func(config *Config) {
  1181  			for i := range config.SessionTicketKey {
  1182  				config.SessionTicketKey[i] = byte(i)
  1183  			}
  1184  			config.sessionTicketKeys = nil
  1185  		},
  1186  		func(clientHello *ClientHelloInfo) (*Config, error) {
  1187  			config := testConfig.Clone()
  1188  			for i := range config.SessionTicketKey {
  1189  				config.SessionTicketKey[i] = 0
  1190  			}
  1191  			config.sessionTicketKeys = nil
  1192  			return config, nil
  1193  		},
  1194  		"",
  1195  		func(config *Config) error {
  1196  			// The value of SessionTicketKey should have been
  1197  			// duplicated into the per-connection Config.
  1198  			for i := range config.SessionTicketKey {
  1199  				if b := config.SessionTicketKey[i]; b != byte(i) {
  1200  					return fmt.Errorf("SessionTicketKey was not duplicated from original Config: byte %d has value %d", i, b)
  1201  				}
  1202  			}
  1203  			return nil
  1204  		},
  1205  	},
  1206  	{
  1207  		func(config *Config) {
  1208  			var dummyKey [32]byte
  1209  			for i := range dummyKey {
  1210  				dummyKey[i] = byte(i)
  1211  			}
  1212  
  1213  			config.SetSessionTicketKeys([][32]byte{dummyKey})
  1214  		},
  1215  		func(clientHello *ClientHelloInfo) (*Config, error) {
  1216  			config := testConfig.Clone()
  1217  			config.sessionTicketKeys = nil
  1218  			return config, nil
  1219  		},
  1220  		"",
  1221  		func(config *Config) error {
  1222  			// The session ticket keys should have been duplicated
  1223  			// into the per-connection Config.
  1224  			if l := len(config.sessionTicketKeys); l != 1 {
  1225  				return fmt.Errorf("got len(sessionTicketKeys) == %d, wanted 1", l)
  1226  			}
  1227  			return nil
  1228  		},
  1229  	},
  1230  }
  1231  
  1232  func TestGetConfigForClient(t *testing.T) {
  1233  	serverConfig := testConfig.Clone()
  1234  	clientConfig := testConfig.Clone()
  1235  	clientConfig.MinVersion = VersionTLS12
  1236  
  1237  	for i, test := range getConfigForClientTests {
  1238  		if test.setup != nil {
  1239  			test.setup(serverConfig)
  1240  		}
  1241  
  1242  		var configReturned *Config
  1243  		serverConfig.GetConfigForClient = func(clientHello *ClientHelloInfo) (*Config, error) {
  1244  			config, err := test.callback(clientHello)
  1245  			configReturned = config
  1246  			return config, err
  1247  		}
  1248  		c, s := net.Pipe()
  1249  		done := make(chan error)
  1250  
  1251  		go func() {
  1252  			defer s.Close()
  1253  			done <- Server(s, serverConfig).Handshake()
  1254  		}()
  1255  
  1256  		clientErr := Client(c, clientConfig).Handshake()
  1257  		c.Close()
  1258  
  1259  		serverErr := <-done
  1260  
  1261  		if len(test.errorSubstring) == 0 {
  1262  			if serverErr != nil || clientErr != nil {
  1263  				t.Errorf("test[%d]: expected no error but got serverErr: %q, clientErr: %q", i, serverErr, clientErr)
  1264  			}
  1265  			if test.verify != nil {
  1266  				if err := test.verify(configReturned); err != nil {
  1267  					t.Errorf("test[%d]: verify returned error: %v", i, err)
  1268  				}
  1269  			}
  1270  		} else {
  1271  			if serverErr == nil {
  1272  				t.Errorf("test[%d]: expected error containing %q but got no error", i, test.errorSubstring)
  1273  			} else if !strings.Contains(serverErr.Error(), test.errorSubstring) {
  1274  				t.Errorf("test[%d]: expected error to contain %q but it was %q", i, test.errorSubstring, serverErr)
  1275  			}
  1276  		}
  1277  	}
  1278  }
  1279  
  1280  func bigFromString(s string) *big.Int {
  1281  	ret := new(big.Int)
  1282  	ret.SetString(s, 10)
  1283  	return ret
  1284  }
  1285  
  1286  func fromHex(s string) []byte {
  1287  	b, _ := hex.DecodeString(s)
  1288  	return b
  1289  }
  1290  
  1291  var testRSACertificate = fromHex("3082024b308201b4a003020102020900e8f09d3fe25beaa6300d06092a864886f70d01010b0500301f310b3009060355040a1302476f3110300e06035504031307476f20526f6f74301e170d3136303130313030303030305a170d3235303130313030303030305a301a310b3009060355040a1302476f310b300906035504031302476f30819f300d06092a864886f70d010101050003818d0030818902818100db467d932e12270648bc062821ab7ec4b6a25dfe1e5245887a3647a5080d92425bc281c0be97799840fb4f6d14fd2b138bc2a52e67d8d4099ed62238b74a0b74732bc234f1d193e596d9747bf3589f6c613cc0b041d4d92b2b2423775b1c3bbd755dce2054cfa163871d1e24c4f31d1a508baab61443ed97a77562f414c852d70203010001a38193308190300e0603551d0f0101ff0404030205a0301d0603551d250416301406082b0601050507030106082b06010505070302300c0603551d130101ff0402300030190603551d0e041204109f91161f43433e49a6de6db680d79f60301b0603551d230414301280104813494d137e1631bba301d5acab6e7b30190603551d1104123010820e6578616d706c652e676f6c616e67300d06092a864886f70d01010b0500038181009d30cc402b5b50a061cbbae55358e1ed8328a9581aa938a495a1ac315a1a84663d43d32dd90bf297dfd320643892243a00bccf9c7db74020015faad3166109a276fd13c3cce10c5ceeb18782f16c04ed73bbb343778d0c1cf10fa1d8408361c94c722b9daedb4606064df4c1b33ec0d1bd42d4dbfe3d1360845c21d33be9fae7")
  1292  
  1293  var testRSACertificateIssuer = fromHex("3082021930820182a003020102020900ca5e4e811a965964300d06092a864886f70d01010b0500301f310b3009060355040a1302476f3110300e06035504031307476f20526f6f74301e170d3136303130313030303030305a170d3235303130313030303030305a301f310b3009060355040a1302476f3110300e06035504031307476f20526f6f7430819f300d06092a864886f70d010101050003818d0030818902818100d667b378bb22f34143b6cd2008236abefaf2852adf3ab05e01329e2c14834f5105df3f3073f99dab5442d45ee5f8f57b0111c8cb682fbb719a86944eebfffef3406206d898b8c1b1887797c9c5006547bb8f00e694b7a063f10839f269f2c34fff7a1f4b21fbcd6bfdfb13ac792d1d11f277b5c5b48600992203059f2a8f8cc50203010001a35d305b300e0603551d0f0101ff040403020204301d0603551d250416301406082b0601050507030106082b06010505070302300f0603551d130101ff040530030101ff30190603551d0e041204104813494d137e1631bba301d5acab6e7b300d06092a864886f70d01010b050003818100c1154b4bab5266221f293766ae4138899bd4c5e36b13cee670ceeaa4cbdf4f6679017e2fe649765af545749fe4249418a56bd38a04b81e261f5ce86b8d5c65413156a50d12449554748c59a30c515bc36a59d38bddf51173e899820b282e40aa78c806526fd184fb6b4cf186ec728edffa585440d2b3225325f7ab580e87dd76")
  1294  
  1295  var testECDSACertificate = fromHex("3082020030820162020900b8bf2d47a0d2ebf4300906072a8648ce3d04013045310b3009060355040613024155311330110603550408130a536f6d652d53746174653121301f060355040a1318496e7465726e6574205769646769747320507479204c7464301e170d3132313132323135303633325a170d3232313132303135303633325a3045310b3009060355040613024155311330110603550408130a536f6d652d53746174653121301f060355040a1318496e7465726e6574205769646769747320507479204c746430819b301006072a8648ce3d020106052b81040023038186000400c4a1edbe98f90b4873367ec316561122f23d53c33b4d213dcd6b75e6f6b0dc9adf26c1bcb287f072327cb3642f1c90bcea6823107efee325c0483a69e0286dd33700ef0462dd0da09c706283d881d36431aa9e9731bd96b068c09b23de76643f1a5c7fe9120e5858b65f70dd9bd8ead5d7f5d5ccb9b69f30665b669a20e227e5bffe3b300906072a8648ce3d040103818c0030818802420188a24febe245c5487d1bacf5ed989dae4770c05e1bb62fbdf1b64db76140d311a2ceee0b7e927eff769dc33b7ea53fcefa10e259ec472d7cacda4e970e15a06fd00242014dfcbe67139c2d050ebd3fa38c25c13313830d9406bbd4377af6ec7ac9862eddd711697f857c56defb31782be4c7780daecbbe9e4e3624317b6a0f399512078f2a")
  1296  
  1297  var testSNICertificate = fromHex("0441883421114c81480804c430820237308201a0a003020102020900e8f09d3fe25beaa6300d06092a864886f70d01010b0500301f310b3009060355040a1302476f3110300e06035504031307476f20526f6f74301e170d3136303130313030303030305a170d3235303130313030303030305a3023310b3009060355040a1302476f311430120603550403130b736e69746573742e636f6d30819f300d06092a864886f70d010101050003818d0030818902818100db467d932e12270648bc062821ab7ec4b6a25dfe1e5245887a3647a5080d92425bc281c0be97799840fb4f6d14fd2b138bc2a52e67d8d4099ed62238b74a0b74732bc234f1d193e596d9747bf3589f6c613cc0b041d4d92b2b2423775b1c3bbd755dce2054cfa163871d1e24c4f31d1a508baab61443ed97a77562f414c852d70203010001a3773075300e0603551d0f0101ff0404030205a0301d0603551d250416301406082b0601050507030106082b06010505070302300c0603551d130101ff0402300030190603551d0e041204109f91161f43433e49a6de6db680d79f60301b0603551d230414301280104813494d137e1631bba301d5acab6e7b300d06092a864886f70d01010b0500038181007beeecff0230dbb2e7a334af65430b7116e09f327c3bbf918107fc9c66cb497493207ae9b4dbb045cb63d605ec1b5dd485bb69124d68fa298dc776699b47632fd6d73cab57042acb26f083c4087459bc5a3bb3ca4d878d7fe31016b7bc9a627438666566e3389bfaeebe6becc9a0093ceed18d0f9ac79d56f3a73f18188988ed")
  1298  
  1299  var testRSAPrivateKey = &rsa.PrivateKey{
  1300  	PublicKey: rsa.PublicKey{
  1301  		N: bigFromString("153980389784927331788354528594524332344709972855165340650588877572729725338415474372475094155672066328274535240275856844648695200875763869073572078279316458648124537905600131008790701752441155668003033945258023841165089852359980273279085783159654751552359397986180318708491098942831252291841441726305535546071"),
  1302  		E: 65537,
  1303  	},
  1304  	D: bigFromString("7746362285745539358014631136245887418412633787074173796862711588221766398229333338511838891484974940633857861775630560092874987828057333663969469797013996401149696897591265769095952887917296740109742927689053276850469671231961384712725169432413343763989564437170644270643461665184965150423819594083121075825"),
  1305  	Primes: []*big.Int{
  1306  		bigFromString("13299275414352936908236095374926261633419699590839189494995965049151460173257838079863316944311313904000258169883815802963543635820059341150014695560313417"),
  1307  		bigFromString("11578103692682951732111718237224894755352163854919244905974423810539077224889290605729035287537520656160688625383765857517518932447378594964220731750802463"),
  1308  	},
  1309  }
  1310  
  1311  var testECDSAPrivateKey = &ecdsa.PrivateKey{
  1312  	PublicKey: ecdsa.PublicKey{
  1313  		Curve: elliptic.P521(),
  1314  		X:     bigFromString("2636411247892461147287360222306590634450676461695221912739908880441342231985950069527906976759812296359387337367668045707086543273113073382714101597903639351"),
  1315  		Y:     bigFromString("3204695818431246682253994090650952614555094516658732116404513121125038617915183037601737180082382202488628239201196033284060130040574800684774115478859677243"),
  1316  	},
  1317  	D: bigFromString("5477294338614160138026852784385529180817726002953041720191098180813046231640184669647735805135001309477695746518160084669446643325196003346204701381388769751"),
  1318  }