github.com/reiver/go@v0.0.0-20150109200633-1d0c7792f172/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 init() {
    41  	testConfig = &Config{
    42  		Time:               func() time.Time { return time.Unix(0, 0) },
    43  		Rand:               zeroSource{},
    44  		Certificates:       make([]Certificate, 2),
    45  		InsecureSkipVerify: true,
    46  		MinVersion:         VersionSSL30,
    47  		MaxVersion:         VersionTLS12,
    48  	}
    49  	testConfig.Certificates[0].Certificate = [][]byte{testRSACertificate}
    50  	testConfig.Certificates[0].PrivateKey = testRSAPrivateKey
    51  	testConfig.Certificates[1].Certificate = [][]byte{testSNICertificate}
    52  	testConfig.Certificates[1].PrivateKey = testRSAPrivateKey
    53  	testConfig.BuildNameToCertificate()
    54  }
    55  
    56  func testClientHelloFailure(t *testing.T, m handshakeMessage, expectedSubStr string) {
    57  	// Create in-memory network connection,
    58  	// send message to server.  Should return
    59  	// expected error.
    60  	c, s := net.Pipe()
    61  	go func() {
    62  		cli := Client(c, testConfig)
    63  		if ch, ok := m.(*clientHelloMsg); ok {
    64  			cli.vers = ch.vers
    65  		}
    66  		cli.writeRecord(recordTypeHandshake, m.marshal())
    67  		c.Close()
    68  	}()
    69  	err := Server(s, testConfig).Handshake()
    70  	s.Close()
    71  	if err == nil || !strings.Contains(err.Error(), expectedSubStr) {
    72  		t.Errorf("Got error: %s; expected to match substring '%s'", err, expectedSubStr)
    73  	}
    74  }
    75  
    76  func TestSimpleError(t *testing.T) {
    77  	testClientHelloFailure(t, &serverHelloDoneMsg{}, "unexpected handshake message")
    78  }
    79  
    80  var badProtocolVersions = []uint16{0x0000, 0x0005, 0x0100, 0x0105, 0x0200, 0x0205}
    81  
    82  func TestRejectBadProtocolVersion(t *testing.T) {
    83  	for _, v := range badProtocolVersions {
    84  		testClientHelloFailure(t, &clientHelloMsg{vers: v}, "unsupported, maximum protocol version")
    85  	}
    86  }
    87  
    88  func TestNoSuiteOverlap(t *testing.T) {
    89  	clientHello := &clientHelloMsg{
    90  		vers:               0x0301,
    91  		cipherSuites:       []uint16{0xff00},
    92  		compressionMethods: []uint8{0},
    93  	}
    94  	testClientHelloFailure(t, clientHello, "no cipher suite supported by both client and server")
    95  }
    96  
    97  func TestNoCompressionOverlap(t *testing.T) {
    98  	clientHello := &clientHelloMsg{
    99  		vers:               0x0301,
   100  		cipherSuites:       []uint16{TLS_RSA_WITH_RC4_128_SHA},
   101  		compressionMethods: []uint8{0xff},
   102  	}
   103  	testClientHelloFailure(t, clientHello, "client does not support uncompressed connections")
   104  }
   105  
   106  func TestRenegotiationExtension(t *testing.T) {
   107  	clientHello := &clientHelloMsg{
   108  		vers:                VersionTLS12,
   109  		compressionMethods:  []uint8{compressionNone},
   110  		random:              make([]byte, 32),
   111  		secureRenegotiation: true,
   112  		cipherSuites:        []uint16{TLS_RSA_WITH_RC4_128_SHA},
   113  	}
   114  
   115  	var buf []byte
   116  	c, s := net.Pipe()
   117  
   118  	go func() {
   119  		cli := Client(c, testConfig)
   120  		cli.vers = clientHello.vers
   121  		cli.writeRecord(recordTypeHandshake, clientHello.marshal())
   122  
   123  		buf = make([]byte, 1024)
   124  		n, err := c.Read(buf)
   125  		if err != nil {
   126  			t.Fatalf("Server read returned error: %s", err)
   127  		}
   128  		buf = buf[:n]
   129  		c.Close()
   130  	}()
   131  
   132  	Server(s, testConfig).Handshake()
   133  
   134  	if len(buf) < 5+4 {
   135  		t.Fatalf("Server returned short message of length %d", len(buf))
   136  	}
   137  	// buf contains a TLS record, with a 5 byte record header and a 4 byte
   138  	// handshake header. The length of the ServerHello is taken from the
   139  	// handshake header.
   140  	serverHelloLen := int(buf[6])<<16 | int(buf[7])<<8 | int(buf[8])
   141  
   142  	var serverHello serverHelloMsg
   143  	// unmarshal expects to be given the handshake header, but
   144  	// serverHelloLen doesn't include it.
   145  	if !serverHello.unmarshal(buf[5 : 9+serverHelloLen]) {
   146  		t.Fatalf("Failed to parse ServerHello")
   147  	}
   148  
   149  	if !serverHello.secureRenegotiation {
   150  		t.Errorf("Secure renegotiation extension was not echoed.")
   151  	}
   152  }
   153  
   154  func TestTLS12OnlyCipherSuites(t *testing.T) {
   155  	// Test that a Server doesn't select a TLS 1.2-only cipher suite when
   156  	// the client negotiates TLS 1.1.
   157  	var zeros [32]byte
   158  
   159  	clientHello := &clientHelloMsg{
   160  		vers:   VersionTLS11,
   161  		random: zeros[:],
   162  		cipherSuites: []uint16{
   163  			// The Server, by default, will use the client's
   164  			// preference order. So the GCM cipher suite
   165  			// will be selected unless it's excluded because
   166  			// of the version in this ClientHello.
   167  			TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
   168  			TLS_RSA_WITH_RC4_128_SHA,
   169  		},
   170  		compressionMethods: []uint8{compressionNone},
   171  		supportedCurves:    []CurveID{CurveP256, CurveP384, CurveP521},
   172  		supportedPoints:    []uint8{pointFormatUncompressed},
   173  	}
   174  
   175  	c, s := net.Pipe()
   176  	var reply interface{}
   177  	var clientErr error
   178  	go func() {
   179  		cli := Client(c, testConfig)
   180  		cli.vers = clientHello.vers
   181  		cli.writeRecord(recordTypeHandshake, clientHello.marshal())
   182  		reply, clientErr = cli.readHandshake()
   183  		c.Close()
   184  	}()
   185  	config := *testConfig
   186  	config.CipherSuites = clientHello.cipherSuites
   187  	Server(s, &config).Handshake()
   188  	s.Close()
   189  	if clientErr != nil {
   190  		t.Fatal(clientErr)
   191  	}
   192  	serverHello, ok := reply.(*serverHelloMsg)
   193  	if !ok {
   194  		t.Fatalf("didn't get ServerHello message in reply. Got %v\n", reply)
   195  	}
   196  	if s := serverHello.cipherSuite; s != TLS_RSA_WITH_RC4_128_SHA {
   197  		t.Fatalf("bad cipher suite from server: %x", s)
   198  	}
   199  }
   200  
   201  func TestAlertForwarding(t *testing.T) {
   202  	c, s := net.Pipe()
   203  	go func() {
   204  		Client(c, testConfig).sendAlert(alertUnknownCA)
   205  		c.Close()
   206  	}()
   207  
   208  	err := Server(s, testConfig).Handshake()
   209  	s.Close()
   210  	if e, ok := err.(*net.OpError); !ok || e.Err != error(alertUnknownCA) {
   211  		t.Errorf("Got error: %s; expected: %s", err, error(alertUnknownCA))
   212  	}
   213  }
   214  
   215  func TestClose(t *testing.T) {
   216  	c, s := net.Pipe()
   217  	go c.Close()
   218  
   219  	err := Server(s, testConfig).Handshake()
   220  	s.Close()
   221  	if err != io.EOF {
   222  		t.Errorf("Got error: %s; expected: %s", err, io.EOF)
   223  	}
   224  }
   225  
   226  func testHandshake(clientConfig, serverConfig *Config) (state ConnectionState, err error) {
   227  	c, s := net.Pipe()
   228  	done := make(chan bool)
   229  	go func() {
   230  		cli := Client(c, clientConfig)
   231  		cli.Handshake()
   232  		c.Close()
   233  		done <- true
   234  	}()
   235  	server := Server(s, serverConfig)
   236  	err = server.Handshake()
   237  	if err == nil {
   238  		state = server.ConnectionState()
   239  	}
   240  	s.Close()
   241  	<-done
   242  	return
   243  }
   244  
   245  func TestVersion(t *testing.T) {
   246  	serverConfig := &Config{
   247  		Certificates: testConfig.Certificates,
   248  		MaxVersion:   VersionTLS11,
   249  	}
   250  	clientConfig := &Config{
   251  		InsecureSkipVerify: true,
   252  	}
   253  	state, err := testHandshake(clientConfig, serverConfig)
   254  	if err != nil {
   255  		t.Fatalf("handshake failed: %s", err)
   256  	}
   257  	if state.Version != VersionTLS11 {
   258  		t.Fatalf("Incorrect version %x, should be %x", state.Version, VersionTLS11)
   259  	}
   260  }
   261  
   262  func TestCipherSuitePreference(t *testing.T) {
   263  	serverConfig := &Config{
   264  		CipherSuites: []uint16{TLS_RSA_WITH_RC4_128_SHA, TLS_RSA_WITH_AES_128_CBC_SHA, TLS_ECDHE_RSA_WITH_RC4_128_SHA},
   265  		Certificates: testConfig.Certificates,
   266  		MaxVersion:   VersionTLS11,
   267  	}
   268  	clientConfig := &Config{
   269  		CipherSuites:       []uint16{TLS_RSA_WITH_AES_128_CBC_SHA, TLS_RSA_WITH_RC4_128_SHA},
   270  		InsecureSkipVerify: true,
   271  	}
   272  	state, err := testHandshake(clientConfig, serverConfig)
   273  	if err != nil {
   274  		t.Fatalf("handshake failed: %s", err)
   275  	}
   276  	if state.CipherSuite != TLS_RSA_WITH_AES_128_CBC_SHA {
   277  		// By default the server should use the client's preference.
   278  		t.Fatalf("Client's preference was not used, got %x", state.CipherSuite)
   279  	}
   280  
   281  	serverConfig.PreferServerCipherSuites = true
   282  	state, err = testHandshake(clientConfig, serverConfig)
   283  	if err != nil {
   284  		t.Fatalf("handshake failed: %s", err)
   285  	}
   286  	if state.CipherSuite != TLS_RSA_WITH_RC4_128_SHA {
   287  		t.Fatalf("Server's preference was not used, got %x", state.CipherSuite)
   288  	}
   289  }
   290  
   291  // Note: see comment in handshake_test.go for details of how the reference
   292  // tests work.
   293  
   294  // serverTest represents a test of the TLS server handshake against a reference
   295  // implementation.
   296  type serverTest struct {
   297  	// name is a freeform string identifying the test and the file in which
   298  	// the expected results will be stored.
   299  	name string
   300  	// command, if not empty, contains a series of arguments for the
   301  	// command to run for the reference server.
   302  	command []string
   303  	// expectedPeerCerts contains a list of PEM blocks of expected
   304  	// certificates from the client.
   305  	expectedPeerCerts []string
   306  	// config, if not nil, contains a custom Config to use for this test.
   307  	config *Config
   308  	// expectAlert, if true, indicates that a fatal alert should be returned
   309  	// when handshaking with the server.
   310  	expectAlert bool
   311  	// expectHandshakeErrorIncluding, when not empty, contains a string
   312  	// that must be a substring of the error resulting from the handshake.
   313  	expectHandshakeErrorIncluding string
   314  	// validate, if not nil, is a function that will be called with the
   315  	// ConnectionState of the resulting connection. It returns false if the
   316  	// ConnectionState is unacceptable.
   317  	validate func(ConnectionState) error
   318  }
   319  
   320  var defaultClientCommand = []string{"openssl", "s_client", "-no_ticket"}
   321  
   322  // connFromCommand starts opens a listening socket and starts the reference
   323  // client to connect to it. It returns a recordingConn that wraps the resulting
   324  // connection.
   325  func (test *serverTest) connFromCommand() (conn *recordingConn, child *exec.Cmd, err error) {
   326  	l, err := net.ListenTCP("tcp", &net.TCPAddr{
   327  		IP:   net.IPv4(127, 0, 0, 1),
   328  		Port: 0,
   329  	})
   330  	if err != nil {
   331  		return nil, nil, err
   332  	}
   333  	defer l.Close()
   334  
   335  	port := l.Addr().(*net.TCPAddr).Port
   336  
   337  	var command []string
   338  	command = append(command, test.command...)
   339  	if len(command) == 0 {
   340  		command = defaultClientCommand
   341  	}
   342  	command = append(command, "-connect")
   343  	command = append(command, fmt.Sprintf("127.0.0.1:%d", port))
   344  	cmd := exec.Command(command[0], command[1:]...)
   345  	cmd.Stdin = nil
   346  	var output bytes.Buffer
   347  	cmd.Stdout = &output
   348  	cmd.Stderr = &output
   349  	if err := cmd.Start(); err != nil {
   350  		return nil, nil, err
   351  	}
   352  
   353  	connChan := make(chan interface{})
   354  	go func() {
   355  		tcpConn, err := l.Accept()
   356  		if err != nil {
   357  			connChan <- err
   358  		}
   359  		connChan <- tcpConn
   360  	}()
   361  
   362  	var tcpConn net.Conn
   363  	select {
   364  	case connOrError := <-connChan:
   365  		if err, ok := connOrError.(error); ok {
   366  			return nil, nil, err
   367  		}
   368  		tcpConn = connOrError.(net.Conn)
   369  	case <-time.After(2 * time.Second):
   370  		output.WriteTo(os.Stdout)
   371  		return nil, nil, errors.New("timed out waiting for connection from child process")
   372  	}
   373  
   374  	record := &recordingConn{
   375  		Conn: tcpConn,
   376  	}
   377  
   378  	return record, cmd, nil
   379  }
   380  
   381  func (test *serverTest) dataPath() string {
   382  	return filepath.Join("testdata", "Server-"+test.name)
   383  }
   384  
   385  func (test *serverTest) loadData() (flows [][]byte, err error) {
   386  	in, err := os.Open(test.dataPath())
   387  	if err != nil {
   388  		return nil, err
   389  	}
   390  	defer in.Close()
   391  	return parseTestData(in)
   392  }
   393  
   394  func (test *serverTest) run(t *testing.T, write bool) {
   395  	var clientConn, serverConn net.Conn
   396  	var recordingConn *recordingConn
   397  	var childProcess *exec.Cmd
   398  
   399  	if write {
   400  		var err error
   401  		recordingConn, childProcess, err = test.connFromCommand()
   402  		if err != nil {
   403  			t.Fatalf("Failed to start subcommand: %s", err)
   404  		}
   405  		serverConn = recordingConn
   406  	} else {
   407  		clientConn, serverConn = net.Pipe()
   408  	}
   409  	config := test.config
   410  	if config == nil {
   411  		config = testConfig
   412  	}
   413  	server := Server(serverConn, config)
   414  	connStateChan := make(chan ConnectionState, 1)
   415  	go func() {
   416  		var err error
   417  		if _, err = server.Write([]byte("hello, world\n")); err != nil {
   418  			t.Logf("Error from Server.Write: %s", err)
   419  		}
   420  		if len(test.expectHandshakeErrorIncluding) > 0 {
   421  			if err == nil {
   422  				t.Errorf("Error expected, but no error returned")
   423  			} else if s := err.Error(); !strings.Contains(s, test.expectHandshakeErrorIncluding) {
   424  				t.Errorf("Error expected containing '%s' but got '%s'", test.expectHandshakeErrorIncluding, s)
   425  			}
   426  		}
   427  		server.Close()
   428  		serverConn.Close()
   429  		connStateChan <- server.ConnectionState()
   430  	}()
   431  
   432  	if !write {
   433  		flows, err := test.loadData()
   434  		if err != nil {
   435  			if !test.expectAlert {
   436  				t.Fatalf("%s: failed to load data from %s", test.name, test.dataPath())
   437  			}
   438  		}
   439  		for i, b := range flows {
   440  			if i%2 == 0 {
   441  				clientConn.Write(b)
   442  				continue
   443  			}
   444  			bb := make([]byte, len(b))
   445  			n, err := io.ReadFull(clientConn, bb)
   446  			if test.expectAlert {
   447  				if err == nil {
   448  					t.Fatal("Expected read failure but read succeeded")
   449  				}
   450  			} else {
   451  				if err != nil {
   452  					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)
   453  				}
   454  				if !bytes.Equal(b, bb) {
   455  					t.Fatalf("%s #%d: mismatch on read: got:%x want:%x", test.name, i+1, bb, b)
   456  				}
   457  			}
   458  		}
   459  		clientConn.Close()
   460  	}
   461  
   462  	connState := <-connStateChan
   463  	peerCerts := connState.PeerCertificates
   464  	if len(peerCerts) == len(test.expectedPeerCerts) {
   465  		for i, peerCert := range peerCerts {
   466  			block, _ := pem.Decode([]byte(test.expectedPeerCerts[i]))
   467  			if !bytes.Equal(block.Bytes, peerCert.Raw) {
   468  				t.Fatalf("%s: mismatch on peer cert %d", test.name, i+1)
   469  			}
   470  		}
   471  	} else {
   472  		t.Fatalf("%s: mismatch on peer list length: %d (wanted) != %d (got)", test.name, len(test.expectedPeerCerts), len(peerCerts))
   473  	}
   474  
   475  	if test.validate != nil {
   476  		if err := test.validate(connState); err != nil {
   477  			t.Fatalf("validate callback returned error: %s", err)
   478  		}
   479  	}
   480  
   481  	if write {
   482  		path := test.dataPath()
   483  		out, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644)
   484  		if err != nil {
   485  			t.Fatalf("Failed to create output file: %s", err)
   486  		}
   487  		defer out.Close()
   488  		recordingConn.Close()
   489  		if len(recordingConn.flows) < 3 {
   490  			childProcess.Stdout.(*bytes.Buffer).WriteTo(os.Stdout)
   491  			if len(test.expectHandshakeErrorIncluding) == 0 {
   492  				t.Fatalf("Handshake failed")
   493  			}
   494  		}
   495  		recordingConn.WriteTo(out)
   496  		fmt.Printf("Wrote %s\n", path)
   497  		childProcess.Wait()
   498  	}
   499  }
   500  
   501  func runServerTestForVersion(t *testing.T, template *serverTest, prefix, option string) {
   502  	test := *template
   503  	test.name = prefix + test.name
   504  	if len(test.command) == 0 {
   505  		test.command = defaultClientCommand
   506  	}
   507  	test.command = append([]string(nil), test.command...)
   508  	test.command = append(test.command, option)
   509  	test.run(t, *update)
   510  }
   511  
   512  func runServerTestSSLv3(t *testing.T, template *serverTest) {
   513  	runServerTestForVersion(t, template, "SSLv3-", "-ssl3")
   514  }
   515  
   516  func runServerTestTLS10(t *testing.T, template *serverTest) {
   517  	runServerTestForVersion(t, template, "TLSv10-", "-tls1")
   518  }
   519  
   520  func runServerTestTLS11(t *testing.T, template *serverTest) {
   521  	runServerTestForVersion(t, template, "TLSv11-", "-tls1_1")
   522  }
   523  
   524  func runServerTestTLS12(t *testing.T, template *serverTest) {
   525  	runServerTestForVersion(t, template, "TLSv12-", "-tls1_2")
   526  }
   527  
   528  func TestHandshakeServerRSARC4(t *testing.T) {
   529  	test := &serverTest{
   530  		name:    "RSA-RC4",
   531  		command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "RC4-SHA"},
   532  	}
   533  	runServerTestSSLv3(t, test)
   534  	runServerTestTLS10(t, test)
   535  	runServerTestTLS11(t, test)
   536  	runServerTestTLS12(t, test)
   537  }
   538  
   539  func TestHandshakeServerRSA3DES(t *testing.T) {
   540  	test := &serverTest{
   541  		name:    "RSA-3DES",
   542  		command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "DES-CBC3-SHA"},
   543  	}
   544  	runServerTestSSLv3(t, test)
   545  	runServerTestTLS10(t, test)
   546  	runServerTestTLS12(t, test)
   547  }
   548  
   549  func TestHandshakeServerRSAAES(t *testing.T) {
   550  	test := &serverTest{
   551  		name:    "RSA-AES",
   552  		command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "AES128-SHA"},
   553  	}
   554  	runServerTestSSLv3(t, test)
   555  	runServerTestTLS10(t, test)
   556  	runServerTestTLS12(t, test)
   557  }
   558  
   559  func TestHandshakeServerAESGCM(t *testing.T) {
   560  	test := &serverTest{
   561  		name:    "RSA-AES-GCM",
   562  		command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "ECDHE-RSA-AES128-GCM-SHA256"},
   563  	}
   564  	runServerTestTLS12(t, test)
   565  }
   566  
   567  func TestHandshakeServerECDHEECDSAAES(t *testing.T) {
   568  	config := *testConfig
   569  	config.Certificates = make([]Certificate, 1)
   570  	config.Certificates[0].Certificate = [][]byte{testECDSACertificate}
   571  	config.Certificates[0].PrivateKey = testECDSAPrivateKey
   572  	config.BuildNameToCertificate()
   573  
   574  	test := &serverTest{
   575  		name:    "ECDHE-ECDSA-AES",
   576  		command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "ECDHE-ECDSA-AES256-SHA"},
   577  		config:  &config,
   578  	}
   579  	runServerTestTLS10(t, test)
   580  	runServerTestTLS12(t, test)
   581  }
   582  
   583  func TestHandshakeServerALPN(t *testing.T) {
   584  	config := *testConfig
   585  	config.NextProtos = []string{"proto1", "proto2"}
   586  
   587  	test := &serverTest{
   588  		name: "ALPN",
   589  		// Note that this needs OpenSSL 1.0.2 because that is the first
   590  		// version that supports the -alpn flag.
   591  		command: []string{"openssl", "s_client", "-alpn", "proto2,proto1"},
   592  		config:  &config,
   593  		validate: func(state ConnectionState) error {
   594  			// The server's preferences should override the client.
   595  			if state.NegotiatedProtocol != "proto1" {
   596  				return fmt.Errorf("Got protocol %q, wanted proto1", state.NegotiatedProtocol)
   597  			}
   598  			return nil
   599  		},
   600  	}
   601  	runServerTestTLS12(t, test)
   602  }
   603  
   604  func TestHandshakeServerALPNNoMatch(t *testing.T) {
   605  	config := *testConfig
   606  	config.NextProtos = []string{"proto3"}
   607  
   608  	test := &serverTest{
   609  		name: "ALPN-NoMatch",
   610  		// Note that this needs OpenSSL 1.0.2 because that is the first
   611  		// version that supports the -alpn flag.
   612  		command: []string{"openssl", "s_client", "-alpn", "proto2,proto1"},
   613  		config:  &config,
   614  		validate: func(state ConnectionState) error {
   615  			// Rather than reject the connection, Go doesn't select
   616  			// a protocol when there is no overlap.
   617  			if state.NegotiatedProtocol != "" {
   618  				return fmt.Errorf("Got protocol %q, wanted ''", state.NegotiatedProtocol)
   619  			}
   620  			return nil
   621  		},
   622  	}
   623  	runServerTestTLS12(t, test)
   624  }
   625  
   626  // TestHandshakeServerSNI involves a client sending an SNI extension of
   627  // "snitest.com", which happens to match the CN of testSNICertificate. The test
   628  // verifies that the server correctly selects that certificate.
   629  func TestHandshakeServerSNI(t *testing.T) {
   630  	test := &serverTest{
   631  		name:    "SNI",
   632  		command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "AES128-SHA", "-servername", "snitest.com"},
   633  	}
   634  	runServerTestTLS12(t, test)
   635  }
   636  
   637  // TestHandshakeServerSNICertForName is similar to TestHandshakeServerSNI, but
   638  // tests the dynamic GetCertificate method
   639  func TestHandshakeServerSNIGetCertificate(t *testing.T) {
   640  	config := *testConfig
   641  
   642  	// Replace the NameToCertificate map with a GetCertificate function
   643  	nameToCert := config.NameToCertificate
   644  	config.NameToCertificate = nil
   645  	config.GetCertificate = func(clientHello *ClientHelloInfo) (*Certificate, error) {
   646  		cert, _ := nameToCert[clientHello.ServerName]
   647  		return cert, nil
   648  	}
   649  	test := &serverTest{
   650  		name:    "SNI",
   651  		command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "AES128-SHA", "-servername", "snitest.com"},
   652  		config:  &config,
   653  	}
   654  	runServerTestTLS12(t, test)
   655  }
   656  
   657  // TestHandshakeServerSNICertForNameNotFound is similar to
   658  // TestHandshakeServerSNICertForName, but tests to make sure that when the
   659  // GetCertificate method doesn't return a cert, we fall back to what's in
   660  // the NameToCertificate map.
   661  func TestHandshakeServerSNIGetCertificateNotFound(t *testing.T) {
   662  	config := *testConfig
   663  
   664  	config.GetCertificate = func(clientHello *ClientHelloInfo) (*Certificate, error) {
   665  		return nil, nil
   666  	}
   667  	test := &serverTest{
   668  		name:    "SNI",
   669  		command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "AES128-SHA", "-servername", "snitest.com"},
   670  		config:  &config,
   671  	}
   672  	runServerTestTLS12(t, test)
   673  }
   674  
   675  // TestHandshakeServerSNICertForNameError tests to make sure that errors in
   676  // GetCertificate result in a tls alert.
   677  func TestHandshakeServerSNIGetCertificateError(t *testing.T) {
   678  	config := *testConfig
   679  
   680  	config.GetCertificate = func(clientHello *ClientHelloInfo) (*Certificate, error) {
   681  		return nil, fmt.Errorf("Test error in GetCertificate")
   682  	}
   683  	test := &serverTest{
   684  		name:        "SNI",
   685  		command:     []string{"openssl", "s_client", "-no_ticket", "-cipher", "AES128-SHA", "-servername", "snitest.com"},
   686  		config:      &config,
   687  		expectAlert: true,
   688  	}
   689  	runServerTestTLS12(t, test)
   690  }
   691  
   692  // TestCipherSuiteCertPreferance ensures that we select an RSA ciphersuite with
   693  // an RSA certificate and an ECDSA ciphersuite with an ECDSA certificate.
   694  func TestCipherSuiteCertPreferenceECDSA(t *testing.T) {
   695  	config := *testConfig
   696  	config.CipherSuites = []uint16{TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA}
   697  	config.PreferServerCipherSuites = true
   698  
   699  	test := &serverTest{
   700  		name:   "CipherSuiteCertPreferenceRSA",
   701  		config: &config,
   702  	}
   703  	runServerTestTLS12(t, test)
   704  
   705  	config = *testConfig
   706  	config.CipherSuites = []uint16{TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA, TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA}
   707  	config.Certificates = []Certificate{
   708  		{
   709  			Certificate: [][]byte{testECDSACertificate},
   710  			PrivateKey:  testECDSAPrivateKey,
   711  		},
   712  	}
   713  	config.BuildNameToCertificate()
   714  	config.PreferServerCipherSuites = true
   715  
   716  	test = &serverTest{
   717  		name:   "CipherSuiteCertPreferenceECDSA",
   718  		config: &config,
   719  	}
   720  	runServerTestTLS12(t, test)
   721  }
   722  
   723  func TestResumption(t *testing.T) {
   724  	sessionFilePath := tempFile("")
   725  	defer os.Remove(sessionFilePath)
   726  
   727  	test := &serverTest{
   728  		name:    "IssueTicket",
   729  		command: []string{"openssl", "s_client", "-cipher", "RC4-SHA", "-sess_out", sessionFilePath},
   730  	}
   731  	runServerTestTLS12(t, test)
   732  
   733  	test = &serverTest{
   734  		name:    "Resume",
   735  		command: []string{"openssl", "s_client", "-cipher", "RC4-SHA", "-sess_in", sessionFilePath},
   736  	}
   737  	runServerTestTLS12(t, test)
   738  }
   739  
   740  func TestResumptionDisabled(t *testing.T) {
   741  	sessionFilePath := tempFile("")
   742  	defer os.Remove(sessionFilePath)
   743  
   744  	config := *testConfig
   745  
   746  	test := &serverTest{
   747  		name:    "IssueTicketPreDisable",
   748  		command: []string{"openssl", "s_client", "-cipher", "RC4-SHA", "-sess_out", sessionFilePath},
   749  		config:  &config,
   750  	}
   751  	runServerTestTLS12(t, test)
   752  
   753  	config.SessionTicketsDisabled = true
   754  
   755  	test = &serverTest{
   756  		name:    "ResumeDisabled",
   757  		command: []string{"openssl", "s_client", "-cipher", "RC4-SHA", "-sess_in", sessionFilePath},
   758  		config:  &config,
   759  	}
   760  	runServerTestTLS12(t, test)
   761  
   762  	// One needs to manually confirm that the handshake in the golden data
   763  	// file for ResumeDisabled does not include a resumption handshake.
   764  }
   765  
   766  func TestFallbackSCSV(t *testing.T) {
   767  	serverConfig := &Config{
   768  		Certificates: testConfig.Certificates,
   769  	}
   770  	test := &serverTest{
   771  		name:   "FallbackSCSV",
   772  		config: serverConfig,
   773  		// OpenSSL 1.0.1j is needed for the -fallback_scsv option.
   774  		command: []string{"openssl", "s_client", "-fallback_scsv"},
   775  		expectHandshakeErrorIncluding: "inppropriate protocol fallback",
   776  	}
   777  	runServerTestTLS11(t, test)
   778  }
   779  
   780  // cert.pem and key.pem were generated with generate_cert.go
   781  // Thus, they have no ExtKeyUsage fields and trigger an error
   782  // when verification is turned on.
   783  
   784  const clientCertificatePEM = `
   785  -----BEGIN CERTIFICATE-----
   786  MIIB7TCCAVigAwIBAgIBADALBgkqhkiG9w0BAQUwJjEQMA4GA1UEChMHQWNtZSBD
   787  bzESMBAGA1UEAxMJMTI3LjAuMC4xMB4XDTExMTIwODA3NTUxMloXDTEyMTIwNzA4
   788  MDAxMlowJjEQMA4GA1UEChMHQWNtZSBDbzESMBAGA1UEAxMJMTI3LjAuMC4xMIGc
   789  MAsGCSqGSIb3DQEBAQOBjAAwgYgCgYBO0Hsx44Jk2VnAwoekXh6LczPHY1PfZpIG
   790  hPZk1Y/kNqcdK+izIDZFI7Xjla7t4PUgnI2V339aEu+H5Fto5OkOdOwEin/ekyfE
   791  ARl6vfLcPRSr0FTKIQzQTW6HLlzF0rtNS0/Otiz3fojsfNcCkXSmHgwa2uNKWi7e
   792  E5xMQIhZkwIDAQABozIwMDAOBgNVHQ8BAf8EBAMCAKAwDQYDVR0OBAYEBAECAwQw
   793  DwYDVR0jBAgwBoAEAQIDBDALBgkqhkiG9w0BAQUDgYEANh+zegx1yW43RmEr1b3A
   794  p0vMRpqBWHyFeSnIyMZn3TJWRSt1tukkqVCavh9a+hoV2cxVlXIWg7nCto/9iIw4
   795  hB2rXZIxE0/9gzvGnfERYraL7KtnvshksBFQRlgXa5kc0x38BvEO5ZaoDPl4ILdE
   796  GFGNEH5PlGffo05wc46QkYU=
   797  -----END CERTIFICATE-----`
   798  
   799  const clientKeyPEM = `
   800  -----BEGIN RSA PRIVATE KEY-----
   801  MIICWgIBAAKBgE7QezHjgmTZWcDCh6ReHotzM8djU99mkgaE9mTVj+Q2px0r6LMg
   802  NkUjteOVru3g9SCcjZXff1oS74fkW2jk6Q507ASKf96TJ8QBGXq98tw9FKvQVMoh
   803  DNBNbocuXMXSu01LT862LPd+iOx81wKRdKYeDBra40paLt4TnExAiFmTAgMBAAEC
   804  gYBxvXd8yNteFTns8A/2yomEMC4yeosJJSpp1CsN3BJ7g8/qTnrVPxBy+RU+qr63
   805  t2WquaOu/cr5P8iEsa6lk20tf8pjKLNXeX0b1RTzK8rJLbS7nGzP3tvOhL096VtQ
   806  dAo4ROEaro0TzYpHmpciSvxVIeEIAAdFDObDJPKqcJAxyQJBAJizfYgK8Gzx9fsx
   807  hxp+VteCbVPg2euASH5Yv3K5LukRdKoSzHE2grUVQgN/LafC0eZibRanxHegYSr7
   808  7qaswKUCQQCEIWor/X4XTMdVj3Oj+vpiw75y/S9gh682+myZL+d/02IEkwnB098P
   809  RkKVpenBHyrGg0oeN5La7URILWKj7CPXAkBKo6F+d+phNjwIFoN1Xb/RA32w/D1I
   810  saG9sF+UEhRt9AxUfW/U/tIQ9V0ZHHcSg1XaCM5Nvp934brdKdvTOKnJAkBD5h/3
   811  Rybatlvg/fzBEaJFyq09zhngkxlZOUtBVTqzl17RVvY2orgH02U4HbCHy4phxOn7
   812  qTdQRYlHRftgnWK1AkANibn9PRYJ7mJyJ9Dyj2QeNcSkSTzrt0tPvUMf4+meJymN
   813  1Ntu5+S1DLLzfxlaljWG6ylW6DNxujCyuXIV2rvA
   814  -----END RSA PRIVATE KEY-----`
   815  
   816  const clientECDSACertificatePEM = `
   817  -----BEGIN CERTIFICATE-----
   818  MIIB/DCCAV4CCQCaMIRsJjXZFzAJBgcqhkjOPQQBMEUxCzAJBgNVBAYTAkFVMRMw
   819  EQYDVQQIEwpTb21lLVN0YXRlMSEwHwYDVQQKExhJbnRlcm5ldCBXaWRnaXRzIFB0
   820  eSBMdGQwHhcNMTIxMTE0MTMyNTUzWhcNMjIxMTEyMTMyNTUzWjBBMQswCQYDVQQG
   821  EwJBVTEMMAoGA1UECBMDTlNXMRAwDgYDVQQHEwdQeXJtb250MRIwEAYDVQQDEwlK
   822  b2VsIFNpbmcwgZswEAYHKoZIzj0CAQYFK4EEACMDgYYABACVjJF1FMBexFe01MNv
   823  ja5oHt1vzobhfm6ySD6B5U7ixohLZNz1MLvT/2XMW/TdtWo+PtAd3kfDdq0Z9kUs
   824  jLzYHQFMH3CQRnZIi4+DzEpcj0B22uCJ7B0rxE4wdihBsmKo+1vx+U56jb0JuK7q
   825  ixgnTy5w/hOWusPTQBbNZU6sER7m8TAJBgcqhkjOPQQBA4GMADCBiAJCAOAUxGBg
   826  C3JosDJdYUoCdFzCgbkWqD8pyDbHgf9stlvZcPE4O1BIKJTLCRpS8V3ujfK58PDa
   827  2RU6+b0DeoeiIzXsAkIBo9SKeDUcSpoj0gq+KxAxnZxfvuiRs9oa9V2jI/Umi0Vw
   828  jWVim34BmT0Y9hCaOGGbLlfk+syxis7iI6CH8OFnUes=
   829  -----END CERTIFICATE-----`
   830  
   831  const clientECDSAKeyPEM = `
   832  -----BEGIN EC PARAMETERS-----
   833  BgUrgQQAIw==
   834  -----END EC PARAMETERS-----
   835  -----BEGIN EC PRIVATE KEY-----
   836  MIHcAgEBBEIBkJN9X4IqZIguiEVKMqeBUP5xtRsEv4HJEtOpOGLELwO53SD78Ew8
   837  k+wLWoqizS3NpQyMtrU8JFdWfj+C57UNkOugBwYFK4EEACOhgYkDgYYABACVjJF1
   838  FMBexFe01MNvja5oHt1vzobhfm6ySD6B5U7ixohLZNz1MLvT/2XMW/TdtWo+PtAd
   839  3kfDdq0Z9kUsjLzYHQFMH3CQRnZIi4+DzEpcj0B22uCJ7B0rxE4wdihBsmKo+1vx
   840  +U56jb0JuK7qixgnTy5w/hOWusPTQBbNZU6sER7m8Q==
   841  -----END EC PRIVATE KEY-----`
   842  
   843  func TestClientAuth(t *testing.T) {
   844  	var certPath, keyPath, ecdsaCertPath, ecdsaKeyPath string
   845  
   846  	if *update {
   847  		certPath = tempFile(clientCertificatePEM)
   848  		defer os.Remove(certPath)
   849  		keyPath = tempFile(clientKeyPEM)
   850  		defer os.Remove(keyPath)
   851  		ecdsaCertPath = tempFile(clientECDSACertificatePEM)
   852  		defer os.Remove(ecdsaCertPath)
   853  		ecdsaKeyPath = tempFile(clientECDSAKeyPEM)
   854  		defer os.Remove(ecdsaKeyPath)
   855  	}
   856  
   857  	config := *testConfig
   858  	config.ClientAuth = RequestClientCert
   859  
   860  	test := &serverTest{
   861  		name:    "ClientAuthRequestedNotGiven",
   862  		command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "RC4-SHA"},
   863  		config:  &config,
   864  	}
   865  	runServerTestTLS12(t, test)
   866  
   867  	test = &serverTest{
   868  		name:              "ClientAuthRequestedAndGiven",
   869  		command:           []string{"openssl", "s_client", "-no_ticket", "-cipher", "RC4-SHA", "-cert", certPath, "-key", keyPath},
   870  		config:            &config,
   871  		expectedPeerCerts: []string{clientCertificatePEM},
   872  	}
   873  	runServerTestTLS12(t, test)
   874  
   875  	test = &serverTest{
   876  		name:              "ClientAuthRequestedAndECDSAGiven",
   877  		command:           []string{"openssl", "s_client", "-no_ticket", "-cipher", "RC4-SHA", "-cert", ecdsaCertPath, "-key", ecdsaKeyPath},
   878  		config:            &config,
   879  		expectedPeerCerts: []string{clientECDSACertificatePEM},
   880  	}
   881  	runServerTestTLS12(t, test)
   882  }
   883  
   884  func bigFromString(s string) *big.Int {
   885  	ret := new(big.Int)
   886  	ret.SetString(s, 10)
   887  	return ret
   888  }
   889  
   890  func fromHex(s string) []byte {
   891  	b, _ := hex.DecodeString(s)
   892  	return b
   893  }
   894  
   895  var testRSACertificate = fromHex("308202b030820219a00302010202090085b0bba48a7fb8ca300d06092a864886f70d01010505003045310b3009060355040613024155311330110603550408130a536f6d652d53746174653121301f060355040a1318496e7465726e6574205769646769747320507479204c7464301e170d3130303432343039303933385a170d3131303432343039303933385a3045310b3009060355040613024155311330110603550408130a536f6d652d53746174653121301f060355040a1318496e7465726e6574205769646769747320507479204c746430819f300d06092a864886f70d010101050003818d0030818902818100bb79d6f517b5e5bf4610d0dc69bee62b07435ad0032d8a7a4385b71452e7a5654c2c78b8238cb5b482e5de1f953b7e62a52ca533d6fe125c7a56fcf506bffa587b263fb5cd04d3d0c921964ac7f4549f5abfef427100fe1899077f7e887d7df10439c4a22edb51c97ce3c04c3b326601cfafb11db8719a1ddbdb896baeda2d790203010001a381a73081a4301d0603551d0e04160414b1ade2855acfcb28db69ce2369ded3268e18883930750603551d23046e306c8014b1ade2855acfcb28db69ce2369ded3268e188839a149a4473045310b3009060355040613024155311330110603550408130a536f6d652d53746174653121301f060355040a1318496e7465726e6574205769646769747320507479204c746482090085b0bba48a7fb8ca300c0603551d13040530030101ff300d06092a864886f70d010105050003818100086c4524c76bb159ab0c52ccf2b014d7879d7a6475b55a9566e4c52b8eae12661feb4f38b36e60d392fdf74108b52513b1187a24fb301dbaed98b917ece7d73159db95d31d78ea50565cd5825a2d5a5f33c4b6d8c97590968c0f5298b5cd981f89205ff2a01ca31b9694dda9fd57e970e8266d71999b266e3850296c90a7bdd9")
   896  
   897  var testECDSACertificate = fromHex("3082020030820162020900b8bf2d47a0d2ebf4300906072a8648ce3d04013045310b3009060355040613024155311330110603550408130a536f6d652d53746174653121301f060355040a1318496e7465726e6574205769646769747320507479204c7464301e170d3132313132323135303633325a170d3232313132303135303633325a3045310b3009060355040613024155311330110603550408130a536f6d652d53746174653121301f060355040a1318496e7465726e6574205769646769747320507479204c746430819b301006072a8648ce3d020106052b81040023038186000400c4a1edbe98f90b4873367ec316561122f23d53c33b4d213dcd6b75e6f6b0dc9adf26c1bcb287f072327cb3642f1c90bcea6823107efee325c0483a69e0286dd33700ef0462dd0da09c706283d881d36431aa9e9731bd96b068c09b23de76643f1a5c7fe9120e5858b65f70dd9bd8ead5d7f5d5ccb9b69f30665b669a20e227e5bffe3b300906072a8648ce3d040103818c0030818802420188a24febe245c5487d1bacf5ed989dae4770c05e1bb62fbdf1b64db76140d311a2ceee0b7e927eff769dc33b7ea53fcefa10e259ec472d7cacda4e970e15a06fd00242014dfcbe67139c2d050ebd3fa38c25c13313830d9406bbd4377af6ec7ac9862eddd711697f857c56defb31782be4c7780daecbbe9e4e3624317b6a0f399512078f2a")
   898  
   899  var testSNICertificate = fromHex("308201f23082015da003020102020100300b06092a864886f70d01010530283110300e060355040a130741636d6520436f311430120603550403130b736e69746573742e636f6d301e170d3132303431313137343033355a170d3133303431313137343533355a30283110300e060355040a130741636d6520436f311430120603550403130b736e69746573742e636f6d30819d300b06092a864886f70d01010103818d0030818902818100bb79d6f517b5e5bf4610d0dc69bee62b07435ad0032d8a7a4385b71452e7a5654c2c78b8238cb5b482e5de1f953b7e62a52ca533d6fe125c7a56fcf506bffa587b263fb5cd04d3d0c921964ac7f4549f5abfef427100fe1899077f7e887d7df10439c4a22edb51c97ce3c04c3b326601cfafb11db8719a1ddbdb896baeda2d790203010001a3323030300e0603551d0f0101ff0404030200a0300d0603551d0e0406040401020304300f0603551d2304083006800401020304300b06092a864886f70d0101050381810089c6455f1c1f5ef8eb1ab174ee2439059f5c4259bb1a8d86cdb1d056f56a717da40e95ab90f59e8deaf627c157995094db0802266eb34fc6842dea8a4b68d9c1389103ab84fb9e1f85d9b5d23ff2312c8670fbb540148245a4ebafe264d90c8a4cf4f85b0fac12ac2fc4a3154bad52462868af96c62c6525d652b6e31845bdcc")
   900  
   901  var testRSAPrivateKey = &rsa.PrivateKey{
   902  	PublicKey: rsa.PublicKey{
   903  		N: bigFromString("131650079503776001033793877885499001334664249354723305978524647182322416328664556247316495448366990052837680518067798333412266673813370895702118944398081598789828837447552603077848001020611640547221687072142537202428102790818451901395596882588063427854225330436740647715202971973145151161964464812406232198521"),
   904  		E: 65537,
   905  	},
   906  	D: bigFromString("29354450337804273969007277378287027274721892607543397931919078829901848876371746653677097639302788129485893852488285045793268732234230875671682624082413996177431586734171663258657462237320300610850244186316880055243099640544518318093544057213190320837094958164973959123058337475052510833916491060913053867729"),
   907  	Primes: []*big.Int{
   908  		bigFromString("11969277782311800166562047708379380720136961987713178380670422671426759650127150688426177829077494755200794297055316163155755835813760102405344560929062149"),
   909  		bigFromString("10998999429884441391899182616418192492905073053684657075974935218461686523870125521822756579792315215543092255516093840728890783887287417039645833477273829"),
   910  	},
   911  }
   912  
   913  var testECDSAPrivateKey = &ecdsa.PrivateKey{
   914  	PublicKey: ecdsa.PublicKey{
   915  		Curve: elliptic.P521(),
   916  		X:     bigFromString("2636411247892461147287360222306590634450676461695221912739908880441342231985950069527906976759812296359387337367668045707086543273113073382714101597903639351"),
   917  		Y:     bigFromString("3204695818431246682253994090650952614555094516658732116404513121125038617915183037601737180082382202488628239201196033284060130040574800684774115478859677243"),
   918  	},
   919  	D: bigFromString("5477294338614160138026852784385529180817726002953041720191098180813046231640184669647735805135001309477695746518160084669446643325196003346204701381388769751"),
   920  }