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