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