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