github.com/sbinet/go@v0.0.0-20160827155028-54d7de7dd62b/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  	var clientConn, serverConn net.Conn
   562  	var recordingConn *recordingConn
   563  	var childProcess *exec.Cmd
   564  
   565  	if write {
   566  		var err error
   567  		recordingConn, childProcess, err = test.connFromCommand()
   568  		if err != nil {
   569  			t.Fatalf("Failed to start subcommand: %s", err)
   570  		}
   571  		serverConn = recordingConn
   572  	} else {
   573  		clientConn, serverConn = net.Pipe()
   574  	}
   575  	config := test.config
   576  	if config == nil {
   577  		config = testConfig
   578  	}
   579  	server := Server(serverConn, config)
   580  	connStateChan := make(chan ConnectionState, 1)
   581  	go func() {
   582  		_, err := server.Write([]byte("hello, world\n"))
   583  		if len(test.expectHandshakeErrorIncluding) > 0 {
   584  			if err == nil {
   585  				t.Errorf("Error expected, but no error returned")
   586  			} else if s := err.Error(); !strings.Contains(s, test.expectHandshakeErrorIncluding) {
   587  				t.Errorf("Error expected containing '%s' but got '%s'", test.expectHandshakeErrorIncluding, s)
   588  			}
   589  		} else {
   590  			if err != nil {
   591  				t.Logf("Error from Server.Write: '%s'", err)
   592  			}
   593  		}
   594  		server.Close()
   595  		serverConn.Close()
   596  		connStateChan <- server.ConnectionState()
   597  	}()
   598  
   599  	if !write {
   600  		flows, err := test.loadData()
   601  		if err != nil {
   602  			t.Fatalf("%s: failed to load data from %s", test.name, test.dataPath())
   603  		}
   604  		for i, b := range flows {
   605  			if i%2 == 0 {
   606  				clientConn.Write(b)
   607  				continue
   608  			}
   609  			bb := make([]byte, len(b))
   610  			n, err := io.ReadFull(clientConn, bb)
   611  			if err != nil {
   612  				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)
   613  			}
   614  			if !bytes.Equal(b, bb) {
   615  				t.Fatalf("%s #%d: mismatch on read: got:%x want:%x", test.name, i+1, bb, b)
   616  			}
   617  		}
   618  		clientConn.Close()
   619  	}
   620  
   621  	connState := <-connStateChan
   622  	peerCerts := connState.PeerCertificates
   623  	if len(peerCerts) == len(test.expectedPeerCerts) {
   624  		for i, peerCert := range peerCerts {
   625  			block, _ := pem.Decode([]byte(test.expectedPeerCerts[i]))
   626  			if !bytes.Equal(block.Bytes, peerCert.Raw) {
   627  				t.Fatalf("%s: mismatch on peer cert %d", test.name, i+1)
   628  			}
   629  		}
   630  	} else {
   631  		t.Fatalf("%s: mismatch on peer list length: %d (wanted) != %d (got)", test.name, len(test.expectedPeerCerts), len(peerCerts))
   632  	}
   633  
   634  	if test.validate != nil {
   635  		if err := test.validate(connState); err != nil {
   636  			t.Fatalf("validate callback returned error: %s", err)
   637  		}
   638  	}
   639  
   640  	if write {
   641  		path := test.dataPath()
   642  		out, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644)
   643  		if err != nil {
   644  			t.Fatalf("Failed to create output file: %s", err)
   645  		}
   646  		defer out.Close()
   647  		recordingConn.Close()
   648  		if len(recordingConn.flows) < 3 {
   649  			childProcess.Stdout.(*bytes.Buffer).WriteTo(os.Stdout)
   650  			if len(test.expectHandshakeErrorIncluding) == 0 {
   651  				t.Fatalf("Handshake failed")
   652  			}
   653  		}
   654  		recordingConn.WriteTo(out)
   655  		fmt.Printf("Wrote %s\n", path)
   656  		childProcess.Wait()
   657  	}
   658  }
   659  
   660  func runServerTestForVersion(t *testing.T, template *serverTest, prefix, option string) {
   661  	test := *template
   662  	test.name = prefix + test.name
   663  	if len(test.command) == 0 {
   664  		test.command = defaultClientCommand
   665  	}
   666  	test.command = append([]string(nil), test.command...)
   667  	test.command = append(test.command, option)
   668  	test.run(t, *update)
   669  }
   670  
   671  func runServerTestSSLv3(t *testing.T, template *serverTest) {
   672  	runServerTestForVersion(t, template, "SSLv3-", "-ssl3")
   673  }
   674  
   675  func runServerTestTLS10(t *testing.T, template *serverTest) {
   676  	runServerTestForVersion(t, template, "TLSv10-", "-tls1")
   677  }
   678  
   679  func runServerTestTLS11(t *testing.T, template *serverTest) {
   680  	runServerTestForVersion(t, template, "TLSv11-", "-tls1_1")
   681  }
   682  
   683  func runServerTestTLS12(t *testing.T, template *serverTest) {
   684  	runServerTestForVersion(t, template, "TLSv12-", "-tls1_2")
   685  }
   686  
   687  func TestHandshakeServerRSARC4(t *testing.T) {
   688  	test := &serverTest{
   689  		name:    "RSA-RC4",
   690  		command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "RC4-SHA"},
   691  	}
   692  	runServerTestSSLv3(t, test)
   693  	runServerTestTLS10(t, test)
   694  	runServerTestTLS11(t, test)
   695  	runServerTestTLS12(t, test)
   696  }
   697  
   698  func TestHandshakeServerRSA3DES(t *testing.T) {
   699  	test := &serverTest{
   700  		name:    "RSA-3DES",
   701  		command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "DES-CBC3-SHA"},
   702  	}
   703  	runServerTestSSLv3(t, test)
   704  	runServerTestTLS10(t, test)
   705  	runServerTestTLS12(t, test)
   706  }
   707  
   708  func TestHandshakeServerRSAAES(t *testing.T) {
   709  	test := &serverTest{
   710  		name:    "RSA-AES",
   711  		command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "AES128-SHA"},
   712  	}
   713  	runServerTestSSLv3(t, test)
   714  	runServerTestTLS10(t, test)
   715  	runServerTestTLS12(t, test)
   716  }
   717  
   718  func TestHandshakeServerAESGCM(t *testing.T) {
   719  	test := &serverTest{
   720  		name:    "RSA-AES-GCM",
   721  		command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "ECDHE-RSA-AES128-GCM-SHA256"},
   722  	}
   723  	runServerTestTLS12(t, test)
   724  }
   725  
   726  func TestHandshakeServerAES256GCMSHA384(t *testing.T) {
   727  	test := &serverTest{
   728  		name:    "RSA-AES256-GCM-SHA384",
   729  		command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "ECDHE-RSA-AES256-GCM-SHA384"},
   730  	}
   731  	runServerTestTLS12(t, test)
   732  }
   733  
   734  func TestHandshakeServerECDHEECDSAAES(t *testing.T) {
   735  	config := testConfig.clone()
   736  	config.Certificates = make([]Certificate, 1)
   737  	config.Certificates[0].Certificate = [][]byte{testECDSACertificate}
   738  	config.Certificates[0].PrivateKey = testECDSAPrivateKey
   739  	config.BuildNameToCertificate()
   740  
   741  	test := &serverTest{
   742  		name:    "ECDHE-ECDSA-AES",
   743  		command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "ECDHE-ECDSA-AES256-SHA"},
   744  		config:  config,
   745  	}
   746  	runServerTestTLS10(t, test)
   747  	runServerTestTLS12(t, test)
   748  }
   749  
   750  func TestHandshakeServerALPN(t *testing.T) {
   751  	config := testConfig.clone()
   752  	config.NextProtos = []string{"proto1", "proto2"}
   753  
   754  	test := &serverTest{
   755  		name: "ALPN",
   756  		// Note that this needs OpenSSL 1.0.2 because that is the first
   757  		// version that supports the -alpn flag.
   758  		command: []string{"openssl", "s_client", "-alpn", "proto2,proto1"},
   759  		config:  config,
   760  		validate: func(state ConnectionState) error {
   761  			// The server's preferences should override the client.
   762  			if state.NegotiatedProtocol != "proto1" {
   763  				return fmt.Errorf("Got protocol %q, wanted proto1", state.NegotiatedProtocol)
   764  			}
   765  			return nil
   766  		},
   767  	}
   768  	runServerTestTLS12(t, test)
   769  }
   770  
   771  func TestHandshakeServerALPNNoMatch(t *testing.T) {
   772  	config := testConfig.clone()
   773  	config.NextProtos = []string{"proto3"}
   774  
   775  	test := &serverTest{
   776  		name: "ALPN-NoMatch",
   777  		// Note that this needs OpenSSL 1.0.2 because that is the first
   778  		// version that supports the -alpn flag.
   779  		command: []string{"openssl", "s_client", "-alpn", "proto2,proto1"},
   780  		config:  config,
   781  		validate: func(state ConnectionState) error {
   782  			// Rather than reject the connection, Go doesn't select
   783  			// a protocol when there is no overlap.
   784  			if state.NegotiatedProtocol != "" {
   785  				return fmt.Errorf("Got protocol %q, wanted ''", state.NegotiatedProtocol)
   786  			}
   787  			return nil
   788  		},
   789  	}
   790  	runServerTestTLS12(t, test)
   791  }
   792  
   793  // TestHandshakeServerSNI involves a client sending an SNI extension of
   794  // "snitest.com", which happens to match the CN of testSNICertificate. The test
   795  // verifies that the server correctly selects that certificate.
   796  func TestHandshakeServerSNI(t *testing.T) {
   797  	test := &serverTest{
   798  		name:    "SNI",
   799  		command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "AES128-SHA", "-servername", "snitest.com"},
   800  	}
   801  	runServerTestTLS12(t, test)
   802  }
   803  
   804  // TestHandshakeServerSNICertForName is similar to TestHandshakeServerSNI, but
   805  // tests the dynamic GetCertificate method
   806  func TestHandshakeServerSNIGetCertificate(t *testing.T) {
   807  	config := testConfig.clone()
   808  
   809  	// Replace the NameToCertificate map with a GetCertificate function
   810  	nameToCert := config.NameToCertificate
   811  	config.NameToCertificate = nil
   812  	config.GetCertificate = func(clientHello *ClientHelloInfo) (*Certificate, error) {
   813  		cert, _ := nameToCert[clientHello.ServerName]
   814  		return cert, nil
   815  	}
   816  	test := &serverTest{
   817  		name:    "SNI-GetCertificate",
   818  		command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "AES128-SHA", "-servername", "snitest.com"},
   819  		config:  config,
   820  	}
   821  	runServerTestTLS12(t, test)
   822  }
   823  
   824  // TestHandshakeServerSNICertForNameNotFound is similar to
   825  // TestHandshakeServerSNICertForName, but tests to make sure that when the
   826  // GetCertificate method doesn't return a cert, we fall back to what's in
   827  // the NameToCertificate map.
   828  func TestHandshakeServerSNIGetCertificateNotFound(t *testing.T) {
   829  	config := testConfig.clone()
   830  
   831  	config.GetCertificate = func(clientHello *ClientHelloInfo) (*Certificate, error) {
   832  		return nil, nil
   833  	}
   834  	test := &serverTest{
   835  		name:    "SNI-GetCertificateNotFound",
   836  		command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "AES128-SHA", "-servername", "snitest.com"},
   837  		config:  config,
   838  	}
   839  	runServerTestTLS12(t, test)
   840  }
   841  
   842  // TestHandshakeServerSNICertForNameError tests to make sure that errors in
   843  // GetCertificate result in a tls alert.
   844  func TestHandshakeServerSNIGetCertificateError(t *testing.T) {
   845  	const errMsg = "TestHandshakeServerSNIGetCertificateError error"
   846  
   847  	serverConfig := testConfig.clone()
   848  	serverConfig.GetCertificate = func(clientHello *ClientHelloInfo) (*Certificate, error) {
   849  		return nil, errors.New(errMsg)
   850  	}
   851  
   852  	clientHello := &clientHelloMsg{
   853  		vers:               VersionTLS10,
   854  		cipherSuites:       []uint16{TLS_RSA_WITH_RC4_128_SHA},
   855  		compressionMethods: []uint8{compressionNone},
   856  		serverName:         "test",
   857  	}
   858  	testClientHelloFailure(t, serverConfig, clientHello, errMsg)
   859  }
   860  
   861  // TestHandshakeServerEmptyCertificates tests that GetCertificates is called in
   862  // the case that Certificates is empty, even without SNI.
   863  func TestHandshakeServerEmptyCertificates(t *testing.T) {
   864  	const errMsg = "TestHandshakeServerEmptyCertificates error"
   865  
   866  	serverConfig := testConfig.clone()
   867  	serverConfig.GetCertificate = func(clientHello *ClientHelloInfo) (*Certificate, error) {
   868  		return nil, errors.New(errMsg)
   869  	}
   870  	serverConfig.Certificates = nil
   871  
   872  	clientHello := &clientHelloMsg{
   873  		vers:               VersionTLS10,
   874  		cipherSuites:       []uint16{TLS_RSA_WITH_RC4_128_SHA},
   875  		compressionMethods: []uint8{compressionNone},
   876  	}
   877  	testClientHelloFailure(t, serverConfig, clientHello, errMsg)
   878  
   879  	// With an empty Certificates and a nil GetCertificate, the server
   880  	// should always return a “no certificates” error.
   881  	serverConfig.GetCertificate = nil
   882  
   883  	clientHello = &clientHelloMsg{
   884  		vers:               VersionTLS10,
   885  		cipherSuites:       []uint16{TLS_RSA_WITH_RC4_128_SHA},
   886  		compressionMethods: []uint8{compressionNone},
   887  	}
   888  	testClientHelloFailure(t, serverConfig, clientHello, "no certificates")
   889  }
   890  
   891  // TestCipherSuiteCertPreferance ensures that we select an RSA ciphersuite with
   892  // an RSA certificate and an ECDSA ciphersuite with an ECDSA certificate.
   893  func TestCipherSuiteCertPreferenceECDSA(t *testing.T) {
   894  	config := testConfig.clone()
   895  	config.CipherSuites = []uint16{TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA}
   896  	config.PreferServerCipherSuites = true
   897  
   898  	test := &serverTest{
   899  		name:   "CipherSuiteCertPreferenceRSA",
   900  		config: config,
   901  	}
   902  	runServerTestTLS12(t, test)
   903  
   904  	config = testConfig.clone()
   905  	config.CipherSuites = []uint16{TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA, TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA}
   906  	config.Certificates = []Certificate{
   907  		{
   908  			Certificate: [][]byte{testECDSACertificate},
   909  			PrivateKey:  testECDSAPrivateKey,
   910  		},
   911  	}
   912  	config.BuildNameToCertificate()
   913  	config.PreferServerCipherSuites = true
   914  
   915  	test = &serverTest{
   916  		name:   "CipherSuiteCertPreferenceECDSA",
   917  		config: config,
   918  	}
   919  	runServerTestTLS12(t, test)
   920  }
   921  
   922  func TestResumption(t *testing.T) {
   923  	sessionFilePath := tempFile("")
   924  	defer os.Remove(sessionFilePath)
   925  
   926  	test := &serverTest{
   927  		name:    "IssueTicket",
   928  		command: []string{"openssl", "s_client", "-cipher", "RC4-SHA", "-sess_out", sessionFilePath},
   929  	}
   930  	runServerTestTLS12(t, test)
   931  
   932  	test = &serverTest{
   933  		name:    "Resume",
   934  		command: []string{"openssl", "s_client", "-cipher", "RC4-SHA", "-sess_in", sessionFilePath},
   935  	}
   936  	runServerTestTLS12(t, test)
   937  }
   938  
   939  func TestResumptionDisabled(t *testing.T) {
   940  	sessionFilePath := tempFile("")
   941  	defer os.Remove(sessionFilePath)
   942  
   943  	config := testConfig.clone()
   944  
   945  	test := &serverTest{
   946  		name:    "IssueTicketPreDisable",
   947  		command: []string{"openssl", "s_client", "-cipher", "RC4-SHA", "-sess_out", sessionFilePath},
   948  		config:  config,
   949  	}
   950  	runServerTestTLS12(t, test)
   951  
   952  	config.SessionTicketsDisabled = true
   953  
   954  	test = &serverTest{
   955  		name:    "ResumeDisabled",
   956  		command: []string{"openssl", "s_client", "-cipher", "RC4-SHA", "-sess_in", sessionFilePath},
   957  		config:  config,
   958  	}
   959  	runServerTestTLS12(t, test)
   960  
   961  	// One needs to manually confirm that the handshake in the golden data
   962  	// file for ResumeDisabled does not include a resumption handshake.
   963  }
   964  
   965  func TestFallbackSCSV(t *testing.T) {
   966  	serverConfig := Config{
   967  		Certificates: testConfig.Certificates,
   968  	}
   969  	test := &serverTest{
   970  		name:   "FallbackSCSV",
   971  		config: &serverConfig,
   972  		// OpenSSL 1.0.1j is needed for the -fallback_scsv option.
   973  		command: []string{"openssl", "s_client", "-fallback_scsv"},
   974  		expectHandshakeErrorIncluding: "inappropriate protocol fallback",
   975  	}
   976  	runServerTestTLS11(t, test)
   977  }
   978  
   979  // clientCertificatePEM and clientKeyPEM were generated with generate_cert.go
   980  // Thus, they have no ExtKeyUsage fields and trigger an error when verification
   981  // is turned on.
   982  
   983  const clientCertificatePEM = `
   984  -----BEGIN CERTIFICATE-----
   985  MIIB7zCCAVigAwIBAgIQXBnBiWWDVW/cC8m5k5/pvDANBgkqhkiG9w0BAQsFADAS
   986  MRAwDgYDVQQKEwdBY21lIENvMB4XDTE2MDgxNzIxNTIzMVoXDTE3MDgxNzIxNTIz
   987  MVowEjEQMA4GA1UEChMHQWNtZSBDbzCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkC
   988  gYEAum+qhr3Pv5/y71yUYHhv6BPy0ZZvzdkybiI3zkH5yl0prOEn2mGi7oHLEMff
   989  NFiVhuk9GeZcJ3NgyI14AvQdpJgJoxlwaTwlYmYqqyIjxXuFOE8uCXMyp70+m63K
   990  hAfmDzr/d8WdQYUAirab7rCkPy1MTOZCPrtRyN1IVPQMjkcCAwEAAaNGMEQwDgYD
   991  VR0PAQH/BAQDAgWgMBMGA1UdJQQMMAoGCCsGAQUFBwMBMAwGA1UdEwEB/wQCMAAw
   992  DwYDVR0RBAgwBocEfwAAATANBgkqhkiG9w0BAQsFAAOBgQBGq0Si+yhU+Fpn+GKU
   993  8ZqyGJ7ysd4dfm92lam6512oFmyc9wnTN+RLKzZ8Aa1B0jLYw9KT+RBrjpW5LBeK
   994  o0RIvFkTgxYEiKSBXCUNmAysEbEoVr4dzWFihAm/1oDGRY2CLLTYg5vbySK3KhIR
   995  e/oCO8HJ/+rJnahJ05XX1Q7lNQ==
   996  -----END CERTIFICATE-----`
   997  
   998  const clientKeyPEM = `
   999  -----BEGIN RSA PRIVATE KEY-----
  1000  MIICXQIBAAKBgQC6b6qGvc+/n/LvXJRgeG/oE/LRlm/N2TJuIjfOQfnKXSms4Sfa
  1001  YaLugcsQx980WJWG6T0Z5lwnc2DIjXgC9B2kmAmjGXBpPCViZiqrIiPFe4U4Ty4J
  1002  czKnvT6brcqEB+YPOv93xZ1BhQCKtpvusKQ/LUxM5kI+u1HI3UhU9AyORwIDAQAB
  1003  AoGAEJZ03q4uuMb7b26WSQsOMeDsftdatT747LGgs3pNRkMJvTb/O7/qJjxoG+Mc
  1004  qeSj0TAZXp+PXXc3ikCECAc+R8rVMfWdmp903XgO/qYtmZGCorxAHEmR80SrfMXv
  1005  PJnznLQWc8U9nphQErR+tTESg7xWEzmFcPKwnZd1xg8ERYkCQQDTGtrFczlB2b/Z
  1006  9TjNMqUlMnTLIk/a/rPE2fLLmAYhK5sHnJdvDURaH2mF4nso0EGtENnTsh6LATnY
  1007  dkrxXGm9AkEA4hXHG2q3MnhgK1Z5hjv+Fnqd+8bcbII9WW4flFs15EKoMgS1w/PJ
  1008  zbsySaSy5IVS8XeShmT9+3lrleed4sy+UwJBAJOOAbxhfXP5r4+5R6ql66jES75w
  1009  jUCVJzJA5ORJrn8g64u2eGK28z/LFQbv9wXgCwfc72R468BdawFSLa/m2EECQGbZ
  1010  rWiFla26IVXV0xcD98VWJsTBZMlgPnSOqoMdM1kSEd4fUmlAYI/dFzV1XYSkOmVr
  1011  FhdZnklmpVDeu27P4c0CQQCuCOup0FlJSBpWY1TTfun/KMBkBatMz0VMA3d7FKIU
  1012  csPezl677Yjo8u1r/KzeI6zLg87Z8E6r6ZWNc9wBSZK6
  1013  -----END RSA PRIVATE KEY-----`
  1014  
  1015  const clientECDSACertificatePEM = `
  1016  -----BEGIN CERTIFICATE-----
  1017  MIIB/DCCAV4CCQCaMIRsJjXZFzAJBgcqhkjOPQQBMEUxCzAJBgNVBAYTAkFVMRMw
  1018  EQYDVQQIEwpTb21lLVN0YXRlMSEwHwYDVQQKExhJbnRlcm5ldCBXaWRnaXRzIFB0
  1019  eSBMdGQwHhcNMTIxMTE0MTMyNTUzWhcNMjIxMTEyMTMyNTUzWjBBMQswCQYDVQQG
  1020  EwJBVTEMMAoGA1UECBMDTlNXMRAwDgYDVQQHEwdQeXJtb250MRIwEAYDVQQDEwlK
  1021  b2VsIFNpbmcwgZswEAYHKoZIzj0CAQYFK4EEACMDgYYABACVjJF1FMBexFe01MNv
  1022  ja5oHt1vzobhfm6ySD6B5U7ixohLZNz1MLvT/2XMW/TdtWo+PtAd3kfDdq0Z9kUs
  1023  jLzYHQFMH3CQRnZIi4+DzEpcj0B22uCJ7B0rxE4wdihBsmKo+1vx+U56jb0JuK7q
  1024  ixgnTy5w/hOWusPTQBbNZU6sER7m8TAJBgcqhkjOPQQBA4GMADCBiAJCAOAUxGBg
  1025  C3JosDJdYUoCdFzCgbkWqD8pyDbHgf9stlvZcPE4O1BIKJTLCRpS8V3ujfK58PDa
  1026  2RU6+b0DeoeiIzXsAkIBo9SKeDUcSpoj0gq+KxAxnZxfvuiRs9oa9V2jI/Umi0Vw
  1027  jWVim34BmT0Y9hCaOGGbLlfk+syxis7iI6CH8OFnUes=
  1028  -----END CERTIFICATE-----`
  1029  
  1030  const clientECDSAKeyPEM = `
  1031  -----BEGIN EC PARAMETERS-----
  1032  BgUrgQQAIw==
  1033  -----END EC PARAMETERS-----
  1034  -----BEGIN EC PRIVATE KEY-----
  1035  MIHcAgEBBEIBkJN9X4IqZIguiEVKMqeBUP5xtRsEv4HJEtOpOGLELwO53SD78Ew8
  1036  k+wLWoqizS3NpQyMtrU8JFdWfj+C57UNkOugBwYFK4EEACOhgYkDgYYABACVjJF1
  1037  FMBexFe01MNvja5oHt1vzobhfm6ySD6B5U7ixohLZNz1MLvT/2XMW/TdtWo+PtAd
  1038  3kfDdq0Z9kUsjLzYHQFMH3CQRnZIi4+DzEpcj0B22uCJ7B0rxE4wdihBsmKo+1vx
  1039  +U56jb0JuK7qixgnTy5w/hOWusPTQBbNZU6sER7m8Q==
  1040  -----END EC PRIVATE KEY-----`
  1041  
  1042  func TestClientAuth(t *testing.T) {
  1043  	var certPath, keyPath, ecdsaCertPath, ecdsaKeyPath string
  1044  
  1045  	if *update {
  1046  		certPath = tempFile(clientCertificatePEM)
  1047  		defer os.Remove(certPath)
  1048  		keyPath = tempFile(clientKeyPEM)
  1049  		defer os.Remove(keyPath)
  1050  		ecdsaCertPath = tempFile(clientECDSACertificatePEM)
  1051  		defer os.Remove(ecdsaCertPath)
  1052  		ecdsaKeyPath = tempFile(clientECDSAKeyPEM)
  1053  		defer os.Remove(ecdsaKeyPath)
  1054  	}
  1055  
  1056  	config := testConfig.clone()
  1057  	config.ClientAuth = RequestClientCert
  1058  
  1059  	test := &serverTest{
  1060  		name:    "ClientAuthRequestedNotGiven",
  1061  		command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "RC4-SHA"},
  1062  		config:  config,
  1063  	}
  1064  	runServerTestTLS12(t, test)
  1065  
  1066  	test = &serverTest{
  1067  		name:              "ClientAuthRequestedAndGiven",
  1068  		command:           []string{"openssl", "s_client", "-no_ticket", "-cipher", "RC4-SHA", "-cert", certPath, "-key", keyPath},
  1069  		config:            config,
  1070  		expectedPeerCerts: []string{clientCertificatePEM},
  1071  	}
  1072  	runServerTestTLS12(t, test)
  1073  
  1074  	test = &serverTest{
  1075  		name:              "ClientAuthRequestedAndECDSAGiven",
  1076  		command:           []string{"openssl", "s_client", "-no_ticket", "-cipher", "RC4-SHA", "-cert", ecdsaCertPath, "-key", ecdsaKeyPath},
  1077  		config:            config,
  1078  		expectedPeerCerts: []string{clientECDSACertificatePEM},
  1079  	}
  1080  	runServerTestTLS12(t, test)
  1081  }
  1082  
  1083  func TestSNIGivenOnFailure(t *testing.T) {
  1084  	const expectedServerName = "test.testing"
  1085  
  1086  	clientHello := &clientHelloMsg{
  1087  		vers:               VersionTLS10,
  1088  		cipherSuites:       []uint16{TLS_RSA_WITH_RC4_128_SHA},
  1089  		compressionMethods: []uint8{compressionNone},
  1090  		serverName:         expectedServerName,
  1091  	}
  1092  
  1093  	serverConfig := testConfig.clone()
  1094  	// Erase the server's cipher suites to ensure the handshake fails.
  1095  	serverConfig.CipherSuites = nil
  1096  
  1097  	c, s := net.Pipe()
  1098  	go func() {
  1099  		cli := Client(c, testConfig)
  1100  		cli.vers = clientHello.vers
  1101  		cli.writeRecord(recordTypeHandshake, clientHello.marshal())
  1102  		c.Close()
  1103  	}()
  1104  	hs := serverHandshakeState{
  1105  		c: Server(s, serverConfig),
  1106  	}
  1107  	_, err := hs.readClientHello()
  1108  	defer s.Close()
  1109  
  1110  	if err == nil {
  1111  		t.Error("No error reported from server")
  1112  	}
  1113  
  1114  	cs := hs.c.ConnectionState()
  1115  	if cs.HandshakeComplete {
  1116  		t.Error("Handshake registered as complete")
  1117  	}
  1118  
  1119  	if cs.ServerName != expectedServerName {
  1120  		t.Errorf("Expected ServerName of %q, but got %q", expectedServerName, cs.ServerName)
  1121  	}
  1122  }
  1123  
  1124  func bigFromString(s string) *big.Int {
  1125  	ret := new(big.Int)
  1126  	ret.SetString(s, 10)
  1127  	return ret
  1128  }
  1129  
  1130  func fromHex(s string) []byte {
  1131  	b, _ := hex.DecodeString(s)
  1132  	return b
  1133  }
  1134  
  1135  var testRSACertificate = fromHex("3082024b308201b4a003020102020900e8f09d3fe25beaa6300d06092a864886f70d01010b0500301f310b3009060355040a1302476f3110300e06035504031307476f20526f6f74301e170d3136303130313030303030305a170d3235303130313030303030305a301a310b3009060355040a1302476f310b300906035504031302476f30819f300d06092a864886f70d010101050003818d0030818902818100db467d932e12270648bc062821ab7ec4b6a25dfe1e5245887a3647a5080d92425bc281c0be97799840fb4f6d14fd2b138bc2a52e67d8d4099ed62238b74a0b74732bc234f1d193e596d9747bf3589f6c613cc0b041d4d92b2b2423775b1c3bbd755dce2054cfa163871d1e24c4f31d1a508baab61443ed97a77562f414c852d70203010001a38193308190300e0603551d0f0101ff0404030205a0301d0603551d250416301406082b0601050507030106082b06010505070302300c0603551d130101ff0402300030190603551d0e041204109f91161f43433e49a6de6db680d79f60301b0603551d230414301280104813494d137e1631bba301d5acab6e7b30190603551d1104123010820e6578616d706c652e676f6c616e67300d06092a864886f70d01010b0500038181009d30cc402b5b50a061cbbae55358e1ed8328a9581aa938a495a1ac315a1a84663d43d32dd90bf297dfd320643892243a00bccf9c7db74020015faad3166109a276fd13c3cce10c5ceeb18782f16c04ed73bbb343778d0c1cf10fa1d8408361c94c722b9daedb4606064df4c1b33ec0d1bd42d4dbfe3d1360845c21d33be9fae7")
  1136  
  1137  var testRSACertificateIssuer = fromHex("3082021930820182a003020102020900ca5e4e811a965964300d06092a864886f70d01010b0500301f310b3009060355040a1302476f3110300e06035504031307476f20526f6f74301e170d3136303130313030303030305a170d3235303130313030303030305a301f310b3009060355040a1302476f3110300e06035504031307476f20526f6f7430819f300d06092a864886f70d010101050003818d0030818902818100d667b378bb22f34143b6cd2008236abefaf2852adf3ab05e01329e2c14834f5105df3f3073f99dab5442d45ee5f8f57b0111c8cb682fbb719a86944eebfffef3406206d898b8c1b1887797c9c5006547bb8f00e694b7a063f10839f269f2c34fff7a1f4b21fbcd6bfdfb13ac792d1d11f277b5c5b48600992203059f2a8f8cc50203010001a35d305b300e0603551d0f0101ff040403020204301d0603551d250416301406082b0601050507030106082b06010505070302300f0603551d130101ff040530030101ff30190603551d0e041204104813494d137e1631bba301d5acab6e7b300d06092a864886f70d01010b050003818100c1154b4bab5266221f293766ae4138899bd4c5e36b13cee670ceeaa4cbdf4f6679017e2fe649765af545749fe4249418a56bd38a04b81e261f5ce86b8d5c65413156a50d12449554748c59a30c515bc36a59d38bddf51173e899820b282e40aa78c806526fd184fb6b4cf186ec728edffa585440d2b3225325f7ab580e87dd76")
  1138  
  1139  var testECDSACertificate = fromHex("3082020030820162020900b8bf2d47a0d2ebf4300906072a8648ce3d04013045310b3009060355040613024155311330110603550408130a536f6d652d53746174653121301f060355040a1318496e7465726e6574205769646769747320507479204c7464301e170d3132313132323135303633325a170d3232313132303135303633325a3045310b3009060355040613024155311330110603550408130a536f6d652d53746174653121301f060355040a1318496e7465726e6574205769646769747320507479204c746430819b301006072a8648ce3d020106052b81040023038186000400c4a1edbe98f90b4873367ec316561122f23d53c33b4d213dcd6b75e6f6b0dc9adf26c1bcb287f072327cb3642f1c90bcea6823107efee325c0483a69e0286dd33700ef0462dd0da09c706283d881d36431aa9e9731bd96b068c09b23de76643f1a5c7fe9120e5858b65f70dd9bd8ead5d7f5d5ccb9b69f30665b669a20e227e5bffe3b300906072a8648ce3d040103818c0030818802420188a24febe245c5487d1bacf5ed989dae4770c05e1bb62fbdf1b64db76140d311a2ceee0b7e927eff769dc33b7ea53fcefa10e259ec472d7cacda4e970e15a06fd00242014dfcbe67139c2d050ebd3fa38c25c13313830d9406bbd4377af6ec7ac9862eddd711697f857c56defb31782be4c7780daecbbe9e4e3624317b6a0f399512078f2a")
  1140  
  1141  var testSNICertificate = fromHex("0441883421114c81480804c430820237308201a0a003020102020900e8f09d3fe25beaa6300d06092a864886f70d01010b0500301f310b3009060355040a1302476f3110300e06035504031307476f20526f6f74301e170d3136303130313030303030305a170d3235303130313030303030305a3023310b3009060355040a1302476f311430120603550403130b736e69746573742e636f6d30819f300d06092a864886f70d010101050003818d0030818902818100db467d932e12270648bc062821ab7ec4b6a25dfe1e5245887a3647a5080d92425bc281c0be97799840fb4f6d14fd2b138bc2a52e67d8d4099ed62238b74a0b74732bc234f1d193e596d9747bf3589f6c613cc0b041d4d92b2b2423775b1c3bbd755dce2054cfa163871d1e24c4f31d1a508baab61443ed97a77562f414c852d70203010001a3773075300e0603551d0f0101ff0404030205a0301d0603551d250416301406082b0601050507030106082b06010505070302300c0603551d130101ff0402300030190603551d0e041204109f91161f43433e49a6de6db680d79f60301b0603551d230414301280104813494d137e1631bba301d5acab6e7b300d06092a864886f70d01010b0500038181007beeecff0230dbb2e7a334af65430b7116e09f327c3bbf918107fc9c66cb497493207ae9b4dbb045cb63d605ec1b5dd485bb69124d68fa298dc776699b47632fd6d73cab57042acb26f083c4087459bc5a3bb3ca4d878d7fe31016b7bc9a627438666566e3389bfaeebe6becc9a0093ceed18d0f9ac79d56f3a73f18188988ed")
  1142  
  1143  var testRSAPrivateKey = &rsa.PrivateKey{
  1144  	PublicKey: rsa.PublicKey{
  1145  		N: bigFromString("153980389784927331788354528594524332344709972855165340650588877572729725338415474372475094155672066328274535240275856844648695200875763869073572078279316458648124537905600131008790701752441155668003033945258023841165089852359980273279085783159654751552359397986180318708491098942831252291841441726305535546071"),
  1146  		E: 65537,
  1147  	},
  1148  	D: bigFromString("7746362285745539358014631136245887418412633787074173796862711588221766398229333338511838891484974940633857861775630560092874987828057333663969469797013996401149696897591265769095952887917296740109742927689053276850469671231961384712725169432413343763989564437170644270643461665184965150423819594083121075825"),
  1149  	Primes: []*big.Int{
  1150  		bigFromString("13299275414352936908236095374926261633419699590839189494995965049151460173257838079863316944311313904000258169883815802963543635820059341150014695560313417"),
  1151  		bigFromString("11578103692682951732111718237224894755352163854919244905974423810539077224889290605729035287537520656160688625383765857517518932447378594964220731750802463"),
  1152  	},
  1153  }
  1154  
  1155  var testECDSAPrivateKey = &ecdsa.PrivateKey{
  1156  	PublicKey: ecdsa.PublicKey{
  1157  		Curve: elliptic.P521(),
  1158  		X:     bigFromString("2636411247892461147287360222306590634450676461695221912739908880441342231985950069527906976759812296359387337367668045707086543273113073382714101597903639351"),
  1159  		Y:     bigFromString("3204695818431246682253994090650952614555094516658732116404513121125038617915183037601737180082382202488628239201196033284060130040574800684774115478859677243"),
  1160  	},
  1161  	D: bigFromString("5477294338614160138026852784385529180817726002953041720191098180813046231640184669647735805135001309477695746518160084669446643325196003346204701381388769751"),
  1162  }