github.com/euank/go@v0.0.0-20160829210321-495514729181/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 TestHandshakeServerKeyLog(t *testing.T) {
   751  	config := testConfig.clone()
   752  	buf := &bytes.Buffer{}
   753  	config.KeyLogWriter = buf
   754  
   755  	test := &serverTest{
   756  		name:    "KeyLogWriter",
   757  		command: []string{"openssl", "s_client"},
   758  		config:  config,
   759  		validate: func(state ConnectionState) error {
   760  			var format, clientRandom, masterSecret string
   761  			if _, err := fmt.Fscanf(buf, "%s %s %s\n", &format, &clientRandom, &masterSecret); err != nil {
   762  				return fmt.Errorf("failed to parse KeyLogWriter: " + err.Error())
   763  			}
   764  			if format != "CLIENT_RANDOM" {
   765  				return fmt.Errorf("got key log format %q, wanted CLIENT_RANDOM", format)
   766  			}
   767  			// Both clientRandom and masterSecret are unpredictable in server handshake test
   768  			if len(clientRandom) != 64 {
   769  				return fmt.Errorf("got wrong length client random in key log %v, wanted 64", len(clientRandom))
   770  			}
   771  			if len(masterSecret) != 96 {
   772  				return fmt.Errorf("got wrong length master secret in key log %v, want 96", len(masterSecret))
   773  			}
   774  
   775  			// buf should contain no more lines
   776  			var trailingGarbage string
   777  			if _, err := fmt.Fscanln(buf, &trailingGarbage); err == nil {
   778  				return fmt.Errorf("expected exactly one key in log, got trailing garbage %q", trailingGarbage)
   779  			}
   780  
   781  			return nil
   782  		},
   783  	}
   784  	runServerTestTLS10(t, test)
   785  }
   786  
   787  func TestHandshakeServerALPN(t *testing.T) {
   788  	config := testConfig.clone()
   789  	config.NextProtos = []string{"proto1", "proto2"}
   790  
   791  	test := &serverTest{
   792  		name: "ALPN",
   793  		// Note that this needs OpenSSL 1.0.2 because that is the first
   794  		// version that supports the -alpn flag.
   795  		command: []string{"openssl", "s_client", "-alpn", "proto2,proto1"},
   796  		config:  config,
   797  		validate: func(state ConnectionState) error {
   798  			// The server's preferences should override the client.
   799  			if state.NegotiatedProtocol != "proto1" {
   800  				return fmt.Errorf("Got protocol %q, wanted proto1", state.NegotiatedProtocol)
   801  			}
   802  			return nil
   803  		},
   804  	}
   805  	runServerTestTLS12(t, test)
   806  }
   807  
   808  func TestHandshakeServerALPNNoMatch(t *testing.T) {
   809  	config := testConfig.clone()
   810  	config.NextProtos = []string{"proto3"}
   811  
   812  	test := &serverTest{
   813  		name: "ALPN-NoMatch",
   814  		// Note that this needs OpenSSL 1.0.2 because that is the first
   815  		// version that supports the -alpn flag.
   816  		command: []string{"openssl", "s_client", "-alpn", "proto2,proto1"},
   817  		config:  config,
   818  		validate: func(state ConnectionState) error {
   819  			// Rather than reject the connection, Go doesn't select
   820  			// a protocol when there is no overlap.
   821  			if state.NegotiatedProtocol != "" {
   822  				return fmt.Errorf("Got protocol %q, wanted ''", state.NegotiatedProtocol)
   823  			}
   824  			return nil
   825  		},
   826  	}
   827  	runServerTestTLS12(t, test)
   828  }
   829  
   830  // TestHandshakeServerSNI involves a client sending an SNI extension of
   831  // "snitest.com", which happens to match the CN of testSNICertificate. The test
   832  // verifies that the server correctly selects that certificate.
   833  func TestHandshakeServerSNI(t *testing.T) {
   834  	test := &serverTest{
   835  		name:    "SNI",
   836  		command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "AES128-SHA", "-servername", "snitest.com"},
   837  	}
   838  	runServerTestTLS12(t, test)
   839  }
   840  
   841  // TestHandshakeServerSNICertForName is similar to TestHandshakeServerSNI, but
   842  // tests the dynamic GetCertificate method
   843  func TestHandshakeServerSNIGetCertificate(t *testing.T) {
   844  	config := testConfig.clone()
   845  
   846  	// Replace the NameToCertificate map with a GetCertificate function
   847  	nameToCert := config.NameToCertificate
   848  	config.NameToCertificate = nil
   849  	config.GetCertificate = func(clientHello *ClientHelloInfo) (*Certificate, error) {
   850  		cert, _ := nameToCert[clientHello.ServerName]
   851  		return cert, nil
   852  	}
   853  	test := &serverTest{
   854  		name:    "SNI-GetCertificate",
   855  		command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "AES128-SHA", "-servername", "snitest.com"},
   856  		config:  config,
   857  	}
   858  	runServerTestTLS12(t, test)
   859  }
   860  
   861  // TestHandshakeServerSNICertForNameNotFound is similar to
   862  // TestHandshakeServerSNICertForName, but tests to make sure that when the
   863  // GetCertificate method doesn't return a cert, we fall back to what's in
   864  // the NameToCertificate map.
   865  func TestHandshakeServerSNIGetCertificateNotFound(t *testing.T) {
   866  	config := testConfig.clone()
   867  
   868  	config.GetCertificate = func(clientHello *ClientHelloInfo) (*Certificate, error) {
   869  		return nil, nil
   870  	}
   871  	test := &serverTest{
   872  		name:    "SNI-GetCertificateNotFound",
   873  		command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "AES128-SHA", "-servername", "snitest.com"},
   874  		config:  config,
   875  	}
   876  	runServerTestTLS12(t, test)
   877  }
   878  
   879  // TestHandshakeServerSNICertForNameError tests to make sure that errors in
   880  // GetCertificate result in a tls alert.
   881  func TestHandshakeServerSNIGetCertificateError(t *testing.T) {
   882  	const errMsg = "TestHandshakeServerSNIGetCertificateError error"
   883  
   884  	serverConfig := testConfig.clone()
   885  	serverConfig.GetCertificate = func(clientHello *ClientHelloInfo) (*Certificate, error) {
   886  		return nil, errors.New(errMsg)
   887  	}
   888  
   889  	clientHello := &clientHelloMsg{
   890  		vers:               VersionTLS10,
   891  		cipherSuites:       []uint16{TLS_RSA_WITH_RC4_128_SHA},
   892  		compressionMethods: []uint8{compressionNone},
   893  		serverName:         "test",
   894  	}
   895  	testClientHelloFailure(t, serverConfig, clientHello, errMsg)
   896  }
   897  
   898  // TestHandshakeServerEmptyCertificates tests that GetCertificates is called in
   899  // the case that Certificates is empty, even without SNI.
   900  func TestHandshakeServerEmptyCertificates(t *testing.T) {
   901  	const errMsg = "TestHandshakeServerEmptyCertificates error"
   902  
   903  	serverConfig := testConfig.clone()
   904  	serverConfig.GetCertificate = func(clientHello *ClientHelloInfo) (*Certificate, error) {
   905  		return nil, errors.New(errMsg)
   906  	}
   907  	serverConfig.Certificates = nil
   908  
   909  	clientHello := &clientHelloMsg{
   910  		vers:               VersionTLS10,
   911  		cipherSuites:       []uint16{TLS_RSA_WITH_RC4_128_SHA},
   912  		compressionMethods: []uint8{compressionNone},
   913  	}
   914  	testClientHelloFailure(t, serverConfig, clientHello, errMsg)
   915  
   916  	// With an empty Certificates and a nil GetCertificate, the server
   917  	// should always return a “no certificates” error.
   918  	serverConfig.GetCertificate = nil
   919  
   920  	clientHello = &clientHelloMsg{
   921  		vers:               VersionTLS10,
   922  		cipherSuites:       []uint16{TLS_RSA_WITH_RC4_128_SHA},
   923  		compressionMethods: []uint8{compressionNone},
   924  	}
   925  	testClientHelloFailure(t, serverConfig, clientHello, "no certificates")
   926  }
   927  
   928  // TestCipherSuiteCertPreferance ensures that we select an RSA ciphersuite with
   929  // an RSA certificate and an ECDSA ciphersuite with an ECDSA certificate.
   930  func TestCipherSuiteCertPreferenceECDSA(t *testing.T) {
   931  	config := testConfig.clone()
   932  	config.CipherSuites = []uint16{TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA}
   933  	config.PreferServerCipherSuites = true
   934  
   935  	test := &serverTest{
   936  		name:   "CipherSuiteCertPreferenceRSA",
   937  		config: config,
   938  	}
   939  	runServerTestTLS12(t, test)
   940  
   941  	config = testConfig.clone()
   942  	config.CipherSuites = []uint16{TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA, TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA}
   943  	config.Certificates = []Certificate{
   944  		{
   945  			Certificate: [][]byte{testECDSACertificate},
   946  			PrivateKey:  testECDSAPrivateKey,
   947  		},
   948  	}
   949  	config.BuildNameToCertificate()
   950  	config.PreferServerCipherSuites = true
   951  
   952  	test = &serverTest{
   953  		name:   "CipherSuiteCertPreferenceECDSA",
   954  		config: config,
   955  	}
   956  	runServerTestTLS12(t, test)
   957  }
   958  
   959  func TestResumption(t *testing.T) {
   960  	sessionFilePath := tempFile("")
   961  	defer os.Remove(sessionFilePath)
   962  
   963  	test := &serverTest{
   964  		name:    "IssueTicket",
   965  		command: []string{"openssl", "s_client", "-cipher", "RC4-SHA", "-sess_out", sessionFilePath},
   966  	}
   967  	runServerTestTLS12(t, test)
   968  
   969  	test = &serverTest{
   970  		name:    "Resume",
   971  		command: []string{"openssl", "s_client", "-cipher", "RC4-SHA", "-sess_in", sessionFilePath},
   972  	}
   973  	runServerTestTLS12(t, test)
   974  }
   975  
   976  func TestResumptionDisabled(t *testing.T) {
   977  	sessionFilePath := tempFile("")
   978  	defer os.Remove(sessionFilePath)
   979  
   980  	config := testConfig.clone()
   981  
   982  	test := &serverTest{
   983  		name:    "IssueTicketPreDisable",
   984  		command: []string{"openssl", "s_client", "-cipher", "RC4-SHA", "-sess_out", sessionFilePath},
   985  		config:  config,
   986  	}
   987  	runServerTestTLS12(t, test)
   988  
   989  	config.SessionTicketsDisabled = true
   990  
   991  	test = &serverTest{
   992  		name:    "ResumeDisabled",
   993  		command: []string{"openssl", "s_client", "-cipher", "RC4-SHA", "-sess_in", sessionFilePath},
   994  		config:  config,
   995  	}
   996  	runServerTestTLS12(t, test)
   997  
   998  	// One needs to manually confirm that the handshake in the golden data
   999  	// file for ResumeDisabled does not include a resumption handshake.
  1000  }
  1001  
  1002  func TestFallbackSCSV(t *testing.T) {
  1003  	serverConfig := Config{
  1004  		Certificates: testConfig.Certificates,
  1005  	}
  1006  	test := &serverTest{
  1007  		name:   "FallbackSCSV",
  1008  		config: &serverConfig,
  1009  		// OpenSSL 1.0.1j is needed for the -fallback_scsv option.
  1010  		command: []string{"openssl", "s_client", "-fallback_scsv"},
  1011  		expectHandshakeErrorIncluding: "inappropriate protocol fallback",
  1012  	}
  1013  	runServerTestTLS11(t, test)
  1014  }
  1015  
  1016  // clientCertificatePEM and clientKeyPEM were generated with generate_cert.go
  1017  // Thus, they have no ExtKeyUsage fields and trigger an error when verification
  1018  // is turned on.
  1019  
  1020  const clientCertificatePEM = `
  1021  -----BEGIN CERTIFICATE-----
  1022  MIIB7zCCAVigAwIBAgIQXBnBiWWDVW/cC8m5k5/pvDANBgkqhkiG9w0BAQsFADAS
  1023  MRAwDgYDVQQKEwdBY21lIENvMB4XDTE2MDgxNzIxNTIzMVoXDTE3MDgxNzIxNTIz
  1024  MVowEjEQMA4GA1UEChMHQWNtZSBDbzCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkC
  1025  gYEAum+qhr3Pv5/y71yUYHhv6BPy0ZZvzdkybiI3zkH5yl0prOEn2mGi7oHLEMff
  1026  NFiVhuk9GeZcJ3NgyI14AvQdpJgJoxlwaTwlYmYqqyIjxXuFOE8uCXMyp70+m63K
  1027  hAfmDzr/d8WdQYUAirab7rCkPy1MTOZCPrtRyN1IVPQMjkcCAwEAAaNGMEQwDgYD
  1028  VR0PAQH/BAQDAgWgMBMGA1UdJQQMMAoGCCsGAQUFBwMBMAwGA1UdEwEB/wQCMAAw
  1029  DwYDVR0RBAgwBocEfwAAATANBgkqhkiG9w0BAQsFAAOBgQBGq0Si+yhU+Fpn+GKU
  1030  8ZqyGJ7ysd4dfm92lam6512oFmyc9wnTN+RLKzZ8Aa1B0jLYw9KT+RBrjpW5LBeK
  1031  o0RIvFkTgxYEiKSBXCUNmAysEbEoVr4dzWFihAm/1oDGRY2CLLTYg5vbySK3KhIR
  1032  e/oCO8HJ/+rJnahJ05XX1Q7lNQ==
  1033  -----END CERTIFICATE-----`
  1034  
  1035  const clientKeyPEM = `
  1036  -----BEGIN RSA PRIVATE KEY-----
  1037  MIICXQIBAAKBgQC6b6qGvc+/n/LvXJRgeG/oE/LRlm/N2TJuIjfOQfnKXSms4Sfa
  1038  YaLugcsQx980WJWG6T0Z5lwnc2DIjXgC9B2kmAmjGXBpPCViZiqrIiPFe4U4Ty4J
  1039  czKnvT6brcqEB+YPOv93xZ1BhQCKtpvusKQ/LUxM5kI+u1HI3UhU9AyORwIDAQAB
  1040  AoGAEJZ03q4uuMb7b26WSQsOMeDsftdatT747LGgs3pNRkMJvTb/O7/qJjxoG+Mc
  1041  qeSj0TAZXp+PXXc3ikCECAc+R8rVMfWdmp903XgO/qYtmZGCorxAHEmR80SrfMXv
  1042  PJnznLQWc8U9nphQErR+tTESg7xWEzmFcPKwnZd1xg8ERYkCQQDTGtrFczlB2b/Z
  1043  9TjNMqUlMnTLIk/a/rPE2fLLmAYhK5sHnJdvDURaH2mF4nso0EGtENnTsh6LATnY
  1044  dkrxXGm9AkEA4hXHG2q3MnhgK1Z5hjv+Fnqd+8bcbII9WW4flFs15EKoMgS1w/PJ
  1045  zbsySaSy5IVS8XeShmT9+3lrleed4sy+UwJBAJOOAbxhfXP5r4+5R6ql66jES75w
  1046  jUCVJzJA5ORJrn8g64u2eGK28z/LFQbv9wXgCwfc72R468BdawFSLa/m2EECQGbZ
  1047  rWiFla26IVXV0xcD98VWJsTBZMlgPnSOqoMdM1kSEd4fUmlAYI/dFzV1XYSkOmVr
  1048  FhdZnklmpVDeu27P4c0CQQCuCOup0FlJSBpWY1TTfun/KMBkBatMz0VMA3d7FKIU
  1049  csPezl677Yjo8u1r/KzeI6zLg87Z8E6r6ZWNc9wBSZK6
  1050  -----END RSA PRIVATE KEY-----`
  1051  
  1052  const clientECDSACertificatePEM = `
  1053  -----BEGIN CERTIFICATE-----
  1054  MIIB/DCCAV4CCQCaMIRsJjXZFzAJBgcqhkjOPQQBMEUxCzAJBgNVBAYTAkFVMRMw
  1055  EQYDVQQIEwpTb21lLVN0YXRlMSEwHwYDVQQKExhJbnRlcm5ldCBXaWRnaXRzIFB0
  1056  eSBMdGQwHhcNMTIxMTE0MTMyNTUzWhcNMjIxMTEyMTMyNTUzWjBBMQswCQYDVQQG
  1057  EwJBVTEMMAoGA1UECBMDTlNXMRAwDgYDVQQHEwdQeXJtb250MRIwEAYDVQQDEwlK
  1058  b2VsIFNpbmcwgZswEAYHKoZIzj0CAQYFK4EEACMDgYYABACVjJF1FMBexFe01MNv
  1059  ja5oHt1vzobhfm6ySD6B5U7ixohLZNz1MLvT/2XMW/TdtWo+PtAd3kfDdq0Z9kUs
  1060  jLzYHQFMH3CQRnZIi4+DzEpcj0B22uCJ7B0rxE4wdihBsmKo+1vx+U56jb0JuK7q
  1061  ixgnTy5w/hOWusPTQBbNZU6sER7m8TAJBgcqhkjOPQQBA4GMADCBiAJCAOAUxGBg
  1062  C3JosDJdYUoCdFzCgbkWqD8pyDbHgf9stlvZcPE4O1BIKJTLCRpS8V3ujfK58PDa
  1063  2RU6+b0DeoeiIzXsAkIBo9SKeDUcSpoj0gq+KxAxnZxfvuiRs9oa9V2jI/Umi0Vw
  1064  jWVim34BmT0Y9hCaOGGbLlfk+syxis7iI6CH8OFnUes=
  1065  -----END CERTIFICATE-----`
  1066  
  1067  const clientECDSAKeyPEM = `
  1068  -----BEGIN EC PARAMETERS-----
  1069  BgUrgQQAIw==
  1070  -----END EC PARAMETERS-----
  1071  -----BEGIN EC PRIVATE KEY-----
  1072  MIHcAgEBBEIBkJN9X4IqZIguiEVKMqeBUP5xtRsEv4HJEtOpOGLELwO53SD78Ew8
  1073  k+wLWoqizS3NpQyMtrU8JFdWfj+C57UNkOugBwYFK4EEACOhgYkDgYYABACVjJF1
  1074  FMBexFe01MNvja5oHt1vzobhfm6ySD6B5U7ixohLZNz1MLvT/2XMW/TdtWo+PtAd
  1075  3kfDdq0Z9kUsjLzYHQFMH3CQRnZIi4+DzEpcj0B22uCJ7B0rxE4wdihBsmKo+1vx
  1076  +U56jb0JuK7qixgnTy5w/hOWusPTQBbNZU6sER7m8Q==
  1077  -----END EC PRIVATE KEY-----`
  1078  
  1079  func TestClientAuth(t *testing.T) {
  1080  	var certPath, keyPath, ecdsaCertPath, ecdsaKeyPath string
  1081  
  1082  	if *update {
  1083  		certPath = tempFile(clientCertificatePEM)
  1084  		defer os.Remove(certPath)
  1085  		keyPath = tempFile(clientKeyPEM)
  1086  		defer os.Remove(keyPath)
  1087  		ecdsaCertPath = tempFile(clientECDSACertificatePEM)
  1088  		defer os.Remove(ecdsaCertPath)
  1089  		ecdsaKeyPath = tempFile(clientECDSAKeyPEM)
  1090  		defer os.Remove(ecdsaKeyPath)
  1091  	}
  1092  
  1093  	config := testConfig.clone()
  1094  	config.ClientAuth = RequestClientCert
  1095  
  1096  	test := &serverTest{
  1097  		name:    "ClientAuthRequestedNotGiven",
  1098  		command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "RC4-SHA"},
  1099  		config:  config,
  1100  	}
  1101  	runServerTestTLS12(t, test)
  1102  
  1103  	test = &serverTest{
  1104  		name:              "ClientAuthRequestedAndGiven",
  1105  		command:           []string{"openssl", "s_client", "-no_ticket", "-cipher", "RC4-SHA", "-cert", certPath, "-key", keyPath},
  1106  		config:            config,
  1107  		expectedPeerCerts: []string{clientCertificatePEM},
  1108  	}
  1109  	runServerTestTLS12(t, test)
  1110  
  1111  	test = &serverTest{
  1112  		name:              "ClientAuthRequestedAndECDSAGiven",
  1113  		command:           []string{"openssl", "s_client", "-no_ticket", "-cipher", "RC4-SHA", "-cert", ecdsaCertPath, "-key", ecdsaKeyPath},
  1114  		config:            config,
  1115  		expectedPeerCerts: []string{clientECDSACertificatePEM},
  1116  	}
  1117  	runServerTestTLS12(t, test)
  1118  }
  1119  
  1120  func TestSNIGivenOnFailure(t *testing.T) {
  1121  	const expectedServerName = "test.testing"
  1122  
  1123  	clientHello := &clientHelloMsg{
  1124  		vers:               VersionTLS10,
  1125  		cipherSuites:       []uint16{TLS_RSA_WITH_RC4_128_SHA},
  1126  		compressionMethods: []uint8{compressionNone},
  1127  		serverName:         expectedServerName,
  1128  	}
  1129  
  1130  	serverConfig := testConfig.clone()
  1131  	// Erase the server's cipher suites to ensure the handshake fails.
  1132  	serverConfig.CipherSuites = nil
  1133  
  1134  	c, s := net.Pipe()
  1135  	go func() {
  1136  		cli := Client(c, testConfig)
  1137  		cli.vers = clientHello.vers
  1138  		cli.writeRecord(recordTypeHandshake, clientHello.marshal())
  1139  		c.Close()
  1140  	}()
  1141  	hs := serverHandshakeState{
  1142  		c: Server(s, serverConfig),
  1143  	}
  1144  	_, err := hs.readClientHello()
  1145  	defer s.Close()
  1146  
  1147  	if err == nil {
  1148  		t.Error("No error reported from server")
  1149  	}
  1150  
  1151  	cs := hs.c.ConnectionState()
  1152  	if cs.HandshakeComplete {
  1153  		t.Error("Handshake registered as complete")
  1154  	}
  1155  
  1156  	if cs.ServerName != expectedServerName {
  1157  		t.Errorf("Expected ServerName of %q, but got %q", expectedServerName, cs.ServerName)
  1158  	}
  1159  }
  1160  
  1161  func bigFromString(s string) *big.Int {
  1162  	ret := new(big.Int)
  1163  	ret.SetString(s, 10)
  1164  	return ret
  1165  }
  1166  
  1167  func fromHex(s string) []byte {
  1168  	b, _ := hex.DecodeString(s)
  1169  	return b
  1170  }
  1171  
  1172  var testRSACertificate = fromHex("3082024b308201b4a003020102020900e8f09d3fe25beaa6300d06092a864886f70d01010b0500301f310b3009060355040a1302476f3110300e06035504031307476f20526f6f74301e170d3136303130313030303030305a170d3235303130313030303030305a301a310b3009060355040a1302476f310b300906035504031302476f30819f300d06092a864886f70d010101050003818d0030818902818100db467d932e12270648bc062821ab7ec4b6a25dfe1e5245887a3647a5080d92425bc281c0be97799840fb4f6d14fd2b138bc2a52e67d8d4099ed62238b74a0b74732bc234f1d193e596d9747bf3589f6c613cc0b041d4d92b2b2423775b1c3bbd755dce2054cfa163871d1e24c4f31d1a508baab61443ed97a77562f414c852d70203010001a38193308190300e0603551d0f0101ff0404030205a0301d0603551d250416301406082b0601050507030106082b06010505070302300c0603551d130101ff0402300030190603551d0e041204109f91161f43433e49a6de6db680d79f60301b0603551d230414301280104813494d137e1631bba301d5acab6e7b30190603551d1104123010820e6578616d706c652e676f6c616e67300d06092a864886f70d01010b0500038181009d30cc402b5b50a061cbbae55358e1ed8328a9581aa938a495a1ac315a1a84663d43d32dd90bf297dfd320643892243a00bccf9c7db74020015faad3166109a276fd13c3cce10c5ceeb18782f16c04ed73bbb343778d0c1cf10fa1d8408361c94c722b9daedb4606064df4c1b33ec0d1bd42d4dbfe3d1360845c21d33be9fae7")
  1173  
  1174  var testRSACertificateIssuer = fromHex("3082021930820182a003020102020900ca5e4e811a965964300d06092a864886f70d01010b0500301f310b3009060355040a1302476f3110300e06035504031307476f20526f6f74301e170d3136303130313030303030305a170d3235303130313030303030305a301f310b3009060355040a1302476f3110300e06035504031307476f20526f6f7430819f300d06092a864886f70d010101050003818d0030818902818100d667b378bb22f34143b6cd2008236abefaf2852adf3ab05e01329e2c14834f5105df3f3073f99dab5442d45ee5f8f57b0111c8cb682fbb719a86944eebfffef3406206d898b8c1b1887797c9c5006547bb8f00e694b7a063f10839f269f2c34fff7a1f4b21fbcd6bfdfb13ac792d1d11f277b5c5b48600992203059f2a8f8cc50203010001a35d305b300e0603551d0f0101ff040403020204301d0603551d250416301406082b0601050507030106082b06010505070302300f0603551d130101ff040530030101ff30190603551d0e041204104813494d137e1631bba301d5acab6e7b300d06092a864886f70d01010b050003818100c1154b4bab5266221f293766ae4138899bd4c5e36b13cee670ceeaa4cbdf4f6679017e2fe649765af545749fe4249418a56bd38a04b81e261f5ce86b8d5c65413156a50d12449554748c59a30c515bc36a59d38bddf51173e899820b282e40aa78c806526fd184fb6b4cf186ec728edffa585440d2b3225325f7ab580e87dd76")
  1175  
  1176  var testECDSACertificate = fromHex("3082020030820162020900b8bf2d47a0d2ebf4300906072a8648ce3d04013045310b3009060355040613024155311330110603550408130a536f6d652d53746174653121301f060355040a1318496e7465726e6574205769646769747320507479204c7464301e170d3132313132323135303633325a170d3232313132303135303633325a3045310b3009060355040613024155311330110603550408130a536f6d652d53746174653121301f060355040a1318496e7465726e6574205769646769747320507479204c746430819b301006072a8648ce3d020106052b81040023038186000400c4a1edbe98f90b4873367ec316561122f23d53c33b4d213dcd6b75e6f6b0dc9adf26c1bcb287f072327cb3642f1c90bcea6823107efee325c0483a69e0286dd33700ef0462dd0da09c706283d881d36431aa9e9731bd96b068c09b23de76643f1a5c7fe9120e5858b65f70dd9bd8ead5d7f5d5ccb9b69f30665b669a20e227e5bffe3b300906072a8648ce3d040103818c0030818802420188a24febe245c5487d1bacf5ed989dae4770c05e1bb62fbdf1b64db76140d311a2ceee0b7e927eff769dc33b7ea53fcefa10e259ec472d7cacda4e970e15a06fd00242014dfcbe67139c2d050ebd3fa38c25c13313830d9406bbd4377af6ec7ac9862eddd711697f857c56defb31782be4c7780daecbbe9e4e3624317b6a0f399512078f2a")
  1177  
  1178  var testSNICertificate = fromHex("0441883421114c81480804c430820237308201a0a003020102020900e8f09d3fe25beaa6300d06092a864886f70d01010b0500301f310b3009060355040a1302476f3110300e06035504031307476f20526f6f74301e170d3136303130313030303030305a170d3235303130313030303030305a3023310b3009060355040a1302476f311430120603550403130b736e69746573742e636f6d30819f300d06092a864886f70d010101050003818d0030818902818100db467d932e12270648bc062821ab7ec4b6a25dfe1e5245887a3647a5080d92425bc281c0be97799840fb4f6d14fd2b138bc2a52e67d8d4099ed62238b74a0b74732bc234f1d193e596d9747bf3589f6c613cc0b041d4d92b2b2423775b1c3bbd755dce2054cfa163871d1e24c4f31d1a508baab61443ed97a77562f414c852d70203010001a3773075300e0603551d0f0101ff0404030205a0301d0603551d250416301406082b0601050507030106082b06010505070302300c0603551d130101ff0402300030190603551d0e041204109f91161f43433e49a6de6db680d79f60301b0603551d230414301280104813494d137e1631bba301d5acab6e7b300d06092a864886f70d01010b0500038181007beeecff0230dbb2e7a334af65430b7116e09f327c3bbf918107fc9c66cb497493207ae9b4dbb045cb63d605ec1b5dd485bb69124d68fa298dc776699b47632fd6d73cab57042acb26f083c4087459bc5a3bb3ca4d878d7fe31016b7bc9a627438666566e3389bfaeebe6becc9a0093ceed18d0f9ac79d56f3a73f18188988ed")
  1179  
  1180  var testRSAPrivateKey = &rsa.PrivateKey{
  1181  	PublicKey: rsa.PublicKey{
  1182  		N: bigFromString("153980389784927331788354528594524332344709972855165340650588877572729725338415474372475094155672066328274535240275856844648695200875763869073572078279316458648124537905600131008790701752441155668003033945258023841165089852359980273279085783159654751552359397986180318708491098942831252291841441726305535546071"),
  1183  		E: 65537,
  1184  	},
  1185  	D: bigFromString("7746362285745539358014631136245887418412633787074173796862711588221766398229333338511838891484974940633857861775630560092874987828057333663969469797013996401149696897591265769095952887917296740109742927689053276850469671231961384712725169432413343763989564437170644270643461665184965150423819594083121075825"),
  1186  	Primes: []*big.Int{
  1187  		bigFromString("13299275414352936908236095374926261633419699590839189494995965049151460173257838079863316944311313904000258169883815802963543635820059341150014695560313417"),
  1188  		bigFromString("11578103692682951732111718237224894755352163854919244905974423810539077224889290605729035287537520656160688625383765857517518932447378594964220731750802463"),
  1189  	},
  1190  }
  1191  
  1192  var testECDSAPrivateKey = &ecdsa.PrivateKey{
  1193  	PublicKey: ecdsa.PublicKey{
  1194  		Curve: elliptic.P521(),
  1195  		X:     bigFromString("2636411247892461147287360222306590634450676461695221912739908880441342231985950069527906976759812296359387337367668045707086543273113073382714101597903639351"),
  1196  		Y:     bigFromString("3204695818431246682253994090650952614555094516658732116404513121125038617915183037601737180082382202488628239201196033284060130040574800684774115478859677243"),
  1197  	},
  1198  	D: bigFromString("5477294338614160138026852784385529180817726002953041720191098180813046231640184669647735805135001309477695746518160084669446643325196003346204701381388769751"),
  1199  }