github.com/gocuntian/go@v0.0.0-20160610041250-fee02d270bf8/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
   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
   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
   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
   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
   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
   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
   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
   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
   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
   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
   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
   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
   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
   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  // cert.pem and key.pem were generated with generate_cert.go
   980  // Thus, they have no ExtKeyUsage fields and trigger an error
   981  // when verification is turned on.
   982  
   983  const clientCertificatePEM = `
   984  -----BEGIN CERTIFICATE-----
   985  MIIB7TCCAVigAwIBAgIBADALBgkqhkiG9w0BAQUwJjEQMA4GA1UEChMHQWNtZSBD
   986  bzESMBAGA1UEAxMJMTI3LjAuMC4xMB4XDTExMTIwODA3NTUxMloXDTEyMTIwNzA4
   987  MDAxMlowJjEQMA4GA1UEChMHQWNtZSBDbzESMBAGA1UEAxMJMTI3LjAuMC4xMIGc
   988  MAsGCSqGSIb3DQEBAQOBjAAwgYgCgYBO0Hsx44Jk2VnAwoekXh6LczPHY1PfZpIG
   989  hPZk1Y/kNqcdK+izIDZFI7Xjla7t4PUgnI2V339aEu+H5Fto5OkOdOwEin/ekyfE
   990  ARl6vfLcPRSr0FTKIQzQTW6HLlzF0rtNS0/Otiz3fojsfNcCkXSmHgwa2uNKWi7e
   991  E5xMQIhZkwIDAQABozIwMDAOBgNVHQ8BAf8EBAMCAKAwDQYDVR0OBAYEBAECAwQw
   992  DwYDVR0jBAgwBoAEAQIDBDALBgkqhkiG9w0BAQUDgYEANh+zegx1yW43RmEr1b3A
   993  p0vMRpqBWHyFeSnIyMZn3TJWRSt1tukkqVCavh9a+hoV2cxVlXIWg7nCto/9iIw4
   994  hB2rXZIxE0/9gzvGnfERYraL7KtnvshksBFQRlgXa5kc0x38BvEO5ZaoDPl4ILdE
   995  GFGNEH5PlGffo05wc46QkYU=
   996  -----END CERTIFICATE-----`
   997  
   998  const clientKeyPEM = `
   999  -----BEGIN RSA PRIVATE KEY-----
  1000  MIICWgIBAAKBgE7QezHjgmTZWcDCh6ReHotzM8djU99mkgaE9mTVj+Q2px0r6LMg
  1001  NkUjteOVru3g9SCcjZXff1oS74fkW2jk6Q507ASKf96TJ8QBGXq98tw9FKvQVMoh
  1002  DNBNbocuXMXSu01LT862LPd+iOx81wKRdKYeDBra40paLt4TnExAiFmTAgMBAAEC
  1003  gYBxvXd8yNteFTns8A/2yomEMC4yeosJJSpp1CsN3BJ7g8/qTnrVPxBy+RU+qr63
  1004  t2WquaOu/cr5P8iEsa6lk20tf8pjKLNXeX0b1RTzK8rJLbS7nGzP3tvOhL096VtQ
  1005  dAo4ROEaro0TzYpHmpciSvxVIeEIAAdFDObDJPKqcJAxyQJBAJizfYgK8Gzx9fsx
  1006  hxp+VteCbVPg2euASH5Yv3K5LukRdKoSzHE2grUVQgN/LafC0eZibRanxHegYSr7
  1007  7qaswKUCQQCEIWor/X4XTMdVj3Oj+vpiw75y/S9gh682+myZL+d/02IEkwnB098P
  1008  RkKVpenBHyrGg0oeN5La7URILWKj7CPXAkBKo6F+d+phNjwIFoN1Xb/RA32w/D1I
  1009  saG9sF+UEhRt9AxUfW/U/tIQ9V0ZHHcSg1XaCM5Nvp934brdKdvTOKnJAkBD5h/3
  1010  Rybatlvg/fzBEaJFyq09zhngkxlZOUtBVTqzl17RVvY2orgH02U4HbCHy4phxOn7
  1011  qTdQRYlHRftgnWK1AkANibn9PRYJ7mJyJ9Dyj2QeNcSkSTzrt0tPvUMf4+meJymN
  1012  1Ntu5+S1DLLzfxlaljWG6ylW6DNxujCyuXIV2rvA
  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
  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 bigFromString(s string) *big.Int {
  1084  	ret := new(big.Int)
  1085  	ret.SetString(s, 10)
  1086  	return ret
  1087  }
  1088  
  1089  func fromHex(s string) []byte {
  1090  	b, _ := hex.DecodeString(s)
  1091  	return b
  1092  }
  1093  
  1094  var testRSACertificate = fromHex("30820263308201cca003020102020900a273000c8100cbf3300d06092a864886f70d01010b0500302b31173015060355040a130e476f6f676c652054455354494e473110300e06035504031307476f20526f6f74301e170d3135303130313030303030305a170d3235303130313030303030305a302631173015060355040a130e476f6f676c652054455354494e47310b300906035504031302476f30819f300d06092a864886f70d010101050003818d0030818902818100af8788f6201b95656c14ab4405af3b4514e3b76dfd00634d957ffe6a623586c04af9187cf6aa255e7a64316600baf48e92afc76bd876d4f35f41cb6e5615971b97c13c123921663d2b16d1bcdb1cc0a7dab7caadbadacbd52150ecde8dabd16b814b8902f3c4bec16c89b14484bd21d1047d9d164df98215f6effad60947f2fb0203010001a38193308190300e0603551d0f0101ff0404030205a0301d0603551d250416301406082b0601050507030106082b06010505070302300c0603551d130101ff0402300030190603551d0e0412041012508d896f1bd1dc544d6ecb695e06f4301b0603551d23041430128010bf3db6a966f2b840cfeab40378481a4130190603551d1104123010820e6578616d706c652e676f6c616e67300d06092a864886f70d01010b050003818100927caf91551218965931a64840d52dd5eebb02a0f5c21e7c9bb3307d3cdc76da4f3dc0faae2d33246b037b1b67591121b511bc77b9d9e06ea82d2e35fa645f223e63106bbeff14866d0df01531a814381e3b84872ccb98ed5176b9b14fdddb9b84048640fa51ddbab48debe346de46b94f86c7f9a4c24134acccf6eab0ab3918")
  1095  
  1096  var testRSACertificateIssuer = fromHex("3082024d308201b6a003020102020827326bd913b7c43d300d06092a864886f70d01010b0500302b31173015060355040a130e476f6f676c652054455354494e473110300e06035504031307476f20526f6f74301e170d3135303130313030303030305a170d3235303130313030303030305a302b31173015060355040a130e476f6f676c652054455354494e473110300e06035504031307476f20526f6f7430819f300d06092a864886f70d010101050003818d0030818902818100f0429a7b9f66a222c8453800452db355b34c4409fee09af2510a6589bfa35bdb4d453200d1de24338d6d5e5a91cc8301628445d6eb4e675927b9c1ea5c0f676acfb0f708ce4f19827e321c1898bf86df9823d5f0b05df2b6779888eff8abbc7f41c6e7d2667386a579b8cbaad3f6fd597cd7c4b187911a425aed1b555c1965190203010001a37a3078300e0603551d0f0101ff040403020204301d0603551d250416301406082b0601050507030106082b06010505070302300f0603551d130101ff040530030101ff30190603551d0e04120410bf3db6a966f2b840cfeab40378481a41301b0603551d23041430128010bf3db6a966f2b840cfeab40378481a41300d06092a864886f70d01010b050003818100586e68c1219ed4f5782b7cfd53cf1a55750a98781b2023f8694bb831fff6d7d4aad1f0ac782b1ec787f00a8956bdd06b4a1063444fcafe955c07d679163a730802c568886a2cf8a3c2ab41176957131c4b9e077ebd7ffbb91fdad8b08b932e9aeefac04923ffdc0aa145563f7f061995317400203578f350e3e566deb29dec5e")
  1097  
  1098  var testECDSACertificate = fromHex("3082020030820162020900b8bf2d47a0d2ebf4300906072a8648ce3d04013045310b3009060355040613024155311330110603550408130a536f6d652d53746174653121301f060355040a1318496e7465726e6574205769646769747320507479204c7464301e170d3132313132323135303633325a170d3232313132303135303633325a3045310b3009060355040613024155311330110603550408130a536f6d652d53746174653121301f060355040a1318496e7465726e6574205769646769747320507479204c746430819b301006072a8648ce3d020106052b81040023038186000400c4a1edbe98f90b4873367ec316561122f23d53c33b4d213dcd6b75e6f6b0dc9adf26c1bcb287f072327cb3642f1c90bcea6823107efee325c0483a69e0286dd33700ef0462dd0da09c706283d881d36431aa9e9731bd96b068c09b23de76643f1a5c7fe9120e5858b65f70dd9bd8ead5d7f5d5ccb9b69f30665b669a20e227e5bffe3b300906072a8648ce3d040103818c0030818802420188a24febe245c5487d1bacf5ed989dae4770c05e1bb62fbdf1b64db76140d311a2ceee0b7e927eff769dc33b7ea53fcefa10e259ec472d7cacda4e970e15a06fd00242014dfcbe67139c2d050ebd3fa38c25c13313830d9406bbd4377af6ec7ac9862eddd711697f857c56defb31782be4c7780daecbbe9e4e3624317b6a0f399512078f2a")
  1099  
  1100  var testSNICertificate = fromHex("308201f23082015da003020102020100300b06092a864886f70d01010530283110300e060355040a130741636d6520436f311430120603550403130b736e69746573742e636f6d301e170d3132303431313137343033355a170d3133303431313137343533355a30283110300e060355040a130741636d6520436f311430120603550403130b736e69746573742e636f6d30819d300b06092a864886f70d01010103818d0030818902818100bb79d6f517b5e5bf4610d0dc69bee62b07435ad0032d8a7a4385b71452e7a5654c2c78b8238cb5b482e5de1f953b7e62a52ca533d6fe125c7a56fcf506bffa587b263fb5cd04d3d0c921964ac7f4549f5abfef427100fe1899077f7e887d7df10439c4a22edb51c97ce3c04c3b326601cfafb11db8719a1ddbdb896baeda2d790203010001a3323030300e0603551d0f0101ff0404030200a0300d0603551d0e0406040401020304300f0603551d2304083006800401020304300b06092a864886f70d0101050381810089c6455f1c1f5ef8eb1ab174ee2439059f5c4259bb1a8d86cdb1d056f56a717da40e95ab90f59e8deaf627c157995094db0802266eb34fc6842dea8a4b68d9c1389103ab84fb9e1f85d9b5d23ff2312c8670fbb540148245a4ebafe264d90c8a4cf4f85b0fac12ac2fc4a3154bad52462868af96c62c6525d652b6e31845bdcc")
  1101  
  1102  var testRSAPrivateKey = &rsa.PrivateKey{
  1103  	PublicKey: rsa.PublicKey{
  1104  		N: bigFromString("123260960069105588390096594560395120585636206567569540256061833976822892593755073841963170165000086278069699238754008398039246547214989242849418349143232951701395321381739566687846006911427966669790845430647688107009232778985142860108863460556510585049041936029324503323373417214453307648498561956908810892027L"),
  1105  		E: 65537,
  1106  	},
  1107  	D: bigFromString("73196363031103823625826315929954946106043759818067219550565550066527203472294428548476778865091068522665312037075674791871635825938217363523103946045078950060973913307430314113074463630778799389010335923241901501086246276485964417618981733827707048660375428006201525399194575538037883519254056917253456403553L"),
  1108  	Primes: []*big.Int{
  1109  		bigFromString("11157426355495284553529769521954035649776033703833034489026848970480272318436419662860715175517581249375929775774910501512841707465207184924996975125010787L"),
  1110  		bigFromString("11047436580963564307160117670964629323534448585520694947919342920137706075617545637058809770319843170934495909554506529982972972247390145716507031692656521L"),
  1111  	},
  1112  }
  1113  
  1114  var testECDSAPrivateKey = &ecdsa.PrivateKey{
  1115  	PublicKey: ecdsa.PublicKey{
  1116  		Curve: elliptic.P521(),
  1117  		X:     bigFromString("2636411247892461147287360222306590634450676461695221912739908880441342231985950069527906976759812296359387337367668045707086543273113073382714101597903639351"),
  1118  		Y:     bigFromString("3204695818431246682253994090650952614555094516658732116404513121125038617915183037601737180082382202488628239201196033284060130040574800684774115478859677243"),
  1119  	},
  1120  	D: bigFromString("5477294338614160138026852784385529180817726002953041720191098180813046231640184669647735805135001309477695746518160084669446643325196003346204701381388769751"),
  1121  }