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