...

Source file src/crypto/tls/handshake_server_test.go

Documentation: crypto/tls

		 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  	"context"
		10  	"crypto"
		11  	"crypto/elliptic"
		12  	"crypto/x509"
		13  	"encoding/pem"
		14  	"errors"
		15  	"fmt"
		16  	"io"
		17  	"net"
		18  	"os"
		19  	"os/exec"
		20  	"path/filepath"
		21  	"runtime"
		22  	"strings"
		23  	"testing"
		24  	"time"
		25  
		26  	"golang.org/x/crypto/curve25519"
		27  )
		28  
		29  func testClientHello(t *testing.T, serverConfig *Config, m handshakeMessage) {
		30  	testClientHelloFailure(t, serverConfig, m, "")
		31  }
		32  
		33  func testClientHelloFailure(t *testing.T, serverConfig *Config, m handshakeMessage, expectedSubStr string) {
		34  	c, s := localPipe(t)
		35  	go func() {
		36  		cli := Client(c, testConfig)
		37  		if ch, ok := m.(*clientHelloMsg); ok {
		38  			cli.vers = ch.vers
		39  		}
		40  		cli.writeRecord(recordTypeHandshake, m.marshal())
		41  		c.Close()
		42  	}()
		43  	ctx := context.Background()
		44  	conn := Server(s, serverConfig)
		45  	ch, err := conn.readClientHello(ctx)
		46  	hs := serverHandshakeState{
		47  		c:					 conn,
		48  		ctx:				 ctx,
		49  		clientHello: ch,
		50  	}
		51  	if err == nil {
		52  		err = hs.processClientHello()
		53  	}
		54  	if err == nil {
		55  		err = hs.pickCipherSuite()
		56  	}
		57  	s.Close()
		58  	if len(expectedSubStr) == 0 {
		59  		if err != nil && err != io.EOF {
		60  			t.Errorf("Got error: %s; expected to succeed", err)
		61  		}
		62  	} else if err == nil || !strings.Contains(err.Error(), expectedSubStr) {
		63  		t.Errorf("Got error: %v; expected to match substring '%s'", err, expectedSubStr)
		64  	}
		65  }
		66  
		67  func TestSimpleError(t *testing.T) {
		68  	testClientHelloFailure(t, testConfig, &serverHelloDoneMsg{}, "unexpected handshake message")
		69  }
		70  
		71  var badProtocolVersions = []uint16{0x0000, 0x0005, 0x0100, 0x0105, 0x0200, 0x0205, VersionSSL30}
		72  
		73  func TestRejectBadProtocolVersion(t *testing.T) {
		74  	config := testConfig.Clone()
		75  	config.MinVersion = VersionSSL30
		76  	for _, v := range badProtocolVersions {
		77  		testClientHelloFailure(t, config, &clientHelloMsg{
		78  			vers:	 v,
		79  			random: make([]byte, 32),
		80  		}, "unsupported versions")
		81  	}
		82  	testClientHelloFailure(t, config, &clientHelloMsg{
		83  		vers:							VersionTLS12,
		84  		supportedVersions: badProtocolVersions,
		85  		random:						make([]byte, 32),
		86  	}, "unsupported versions")
		87  }
		88  
		89  func TestNoSuiteOverlap(t *testing.T) {
		90  	clientHello := &clientHelloMsg{
		91  		vers:							 VersionTLS10,
		92  		random:						 make([]byte, 32),
		93  		cipherSuites:			 []uint16{0xff00},
		94  		compressionMethods: []uint8{compressionNone},
		95  	}
		96  	testClientHelloFailure(t, testConfig, clientHello, "no cipher suite supported by both client and server")
		97  }
		98  
		99  func TestNoCompressionOverlap(t *testing.T) {
	 100  	clientHello := &clientHelloMsg{
	 101  		vers:							 VersionTLS10,
	 102  		random:						 make([]byte, 32),
	 103  		cipherSuites:			 []uint16{TLS_RSA_WITH_RC4_128_SHA},
	 104  		compressionMethods: []uint8{0xff},
	 105  	}
	 106  	testClientHelloFailure(t, testConfig, clientHello, "client does not support uncompressed connections")
	 107  }
	 108  
	 109  func TestNoRC4ByDefault(t *testing.T) {
	 110  	clientHello := &clientHelloMsg{
	 111  		vers:							 VersionTLS10,
	 112  		random:						 make([]byte, 32),
	 113  		cipherSuites:			 []uint16{TLS_RSA_WITH_RC4_128_SHA},
	 114  		compressionMethods: []uint8{compressionNone},
	 115  	}
	 116  	serverConfig := testConfig.Clone()
	 117  	// Reset the enabled cipher suites to nil in order to test the
	 118  	// defaults.
	 119  	serverConfig.CipherSuites = nil
	 120  	testClientHelloFailure(t, serverConfig, clientHello, "no cipher suite supported by both client and server")
	 121  }
	 122  
	 123  func TestRejectSNIWithTrailingDot(t *testing.T) {
	 124  	testClientHelloFailure(t, testConfig, &clientHelloMsg{
	 125  		vers:			 VersionTLS12,
	 126  		random:		 make([]byte, 32),
	 127  		serverName: "foo.com.",
	 128  	}, "unexpected message")
	 129  }
	 130  
	 131  func TestDontSelectECDSAWithRSAKey(t *testing.T) {
	 132  	// Test that, even when both sides support an ECDSA cipher suite, it
	 133  	// won't be selected if the server's private key doesn't support it.
	 134  	clientHello := &clientHelloMsg{
	 135  		vers:							 VersionTLS10,
	 136  		random:						 make([]byte, 32),
	 137  		cipherSuites:			 []uint16{TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA},
	 138  		compressionMethods: []uint8{compressionNone},
	 139  		supportedCurves:		[]CurveID{CurveP256},
	 140  		supportedPoints:		[]uint8{pointFormatUncompressed},
	 141  	}
	 142  	serverConfig := testConfig.Clone()
	 143  	serverConfig.CipherSuites = clientHello.cipherSuites
	 144  	serverConfig.Certificates = make([]Certificate, 1)
	 145  	serverConfig.Certificates[0].Certificate = [][]byte{testECDSACertificate}
	 146  	serverConfig.Certificates[0].PrivateKey = testECDSAPrivateKey
	 147  	serverConfig.BuildNameToCertificate()
	 148  	// First test that it *does* work when the server's key is ECDSA.
	 149  	testClientHello(t, serverConfig, clientHello)
	 150  
	 151  	// Now test that switching to an RSA key causes the expected error (and
	 152  	// not an internal error about a signing failure).
	 153  	serverConfig.Certificates = testConfig.Certificates
	 154  	testClientHelloFailure(t, serverConfig, clientHello, "no cipher suite supported by both client and server")
	 155  }
	 156  
	 157  func TestDontSelectRSAWithECDSAKey(t *testing.T) {
	 158  	// Test that, even when both sides support an RSA cipher suite, it
	 159  	// won't be selected if the server's private key doesn't support it.
	 160  	clientHello := &clientHelloMsg{
	 161  		vers:							 VersionTLS10,
	 162  		random:						 make([]byte, 32),
	 163  		cipherSuites:			 []uint16{TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA},
	 164  		compressionMethods: []uint8{compressionNone},
	 165  		supportedCurves:		[]CurveID{CurveP256},
	 166  		supportedPoints:		[]uint8{pointFormatUncompressed},
	 167  	}
	 168  	serverConfig := testConfig.Clone()
	 169  	serverConfig.CipherSuites = clientHello.cipherSuites
	 170  	// First test that it *does* work when the server's key is RSA.
	 171  	testClientHello(t, serverConfig, clientHello)
	 172  
	 173  	// Now test that switching to an ECDSA key causes the expected error
	 174  	// (and not an internal error about a signing failure).
	 175  	serverConfig.Certificates = make([]Certificate, 1)
	 176  	serverConfig.Certificates[0].Certificate = [][]byte{testECDSACertificate}
	 177  	serverConfig.Certificates[0].PrivateKey = testECDSAPrivateKey
	 178  	serverConfig.BuildNameToCertificate()
	 179  	testClientHelloFailure(t, serverConfig, clientHello, "no cipher suite supported by both client and server")
	 180  }
	 181  
	 182  func TestRenegotiationExtension(t *testing.T) {
	 183  	clientHello := &clientHelloMsg{
	 184  		vers:												 VersionTLS12,
	 185  		compressionMethods:					 []uint8{compressionNone},
	 186  		random:											 make([]byte, 32),
	 187  		secureRenegotiationSupported: true,
	 188  		cipherSuites:								 []uint16{TLS_RSA_WITH_RC4_128_SHA},
	 189  	}
	 190  
	 191  	bufChan := make(chan []byte, 1)
	 192  	c, s := localPipe(t)
	 193  
	 194  	go func() {
	 195  		cli := Client(c, testConfig)
	 196  		cli.vers = clientHello.vers
	 197  		cli.writeRecord(recordTypeHandshake, clientHello.marshal())
	 198  
	 199  		buf := make([]byte, 1024)
	 200  		n, err := c.Read(buf)
	 201  		if err != nil {
	 202  			t.Errorf("Server read returned error: %s", err)
	 203  			return
	 204  		}
	 205  		c.Close()
	 206  		bufChan <- buf[:n]
	 207  	}()
	 208  
	 209  	Server(s, testConfig).Handshake()
	 210  	buf := <-bufChan
	 211  
	 212  	if len(buf) < 5+4 {
	 213  		t.Fatalf("Server returned short message of length %d", len(buf))
	 214  	}
	 215  	// buf contains a TLS record, with a 5 byte record header and a 4 byte
	 216  	// handshake header. The length of the ServerHello is taken from the
	 217  	// handshake header.
	 218  	serverHelloLen := int(buf[6])<<16 | int(buf[7])<<8 | int(buf[8])
	 219  
	 220  	var serverHello serverHelloMsg
	 221  	// unmarshal expects to be given the handshake header, but
	 222  	// serverHelloLen doesn't include it.
	 223  	if !serverHello.unmarshal(buf[5 : 9+serverHelloLen]) {
	 224  		t.Fatalf("Failed to parse ServerHello")
	 225  	}
	 226  
	 227  	if !serverHello.secureRenegotiationSupported {
	 228  		t.Errorf("Secure renegotiation extension was not echoed.")
	 229  	}
	 230  }
	 231  
	 232  func TestTLS12OnlyCipherSuites(t *testing.T) {
	 233  	// Test that a Server doesn't select a TLS 1.2-only cipher suite when
	 234  	// the client negotiates TLS 1.1.
	 235  	clientHello := &clientHelloMsg{
	 236  		vers:	 VersionTLS11,
	 237  		random: make([]byte, 32),
	 238  		cipherSuites: []uint16{
	 239  			// The Server, by default, will use the client's
	 240  			// preference order. So the GCM cipher suite
	 241  			// will be selected unless it's excluded because
	 242  			// of the version in this ClientHello.
	 243  			TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
	 244  			TLS_RSA_WITH_RC4_128_SHA,
	 245  		},
	 246  		compressionMethods: []uint8{compressionNone},
	 247  		supportedCurves:		[]CurveID{CurveP256, CurveP384, CurveP521},
	 248  		supportedPoints:		[]uint8{pointFormatUncompressed},
	 249  	}
	 250  
	 251  	c, s := localPipe(t)
	 252  	replyChan := make(chan interface{})
	 253  	go func() {
	 254  		cli := Client(c, testConfig)
	 255  		cli.vers = clientHello.vers
	 256  		cli.writeRecord(recordTypeHandshake, clientHello.marshal())
	 257  		reply, err := cli.readHandshake()
	 258  		c.Close()
	 259  		if err != nil {
	 260  			replyChan <- err
	 261  		} else {
	 262  			replyChan <- reply
	 263  		}
	 264  	}()
	 265  	config := testConfig.Clone()
	 266  	config.CipherSuites = clientHello.cipherSuites
	 267  	Server(s, config).Handshake()
	 268  	s.Close()
	 269  	reply := <-replyChan
	 270  	if err, ok := reply.(error); ok {
	 271  		t.Fatal(err)
	 272  	}
	 273  	serverHello, ok := reply.(*serverHelloMsg)
	 274  	if !ok {
	 275  		t.Fatalf("didn't get ServerHello message in reply. Got %v\n", reply)
	 276  	}
	 277  	if s := serverHello.cipherSuite; s != TLS_RSA_WITH_RC4_128_SHA {
	 278  		t.Fatalf("bad cipher suite from server: %x", s)
	 279  	}
	 280  }
	 281  
	 282  func TestTLSPointFormats(t *testing.T) {
	 283  	// Test that a Server returns the ec_point_format extension when ECC is
	 284  	// negotiated, and not returned on RSA handshake.
	 285  	tests := []struct {
	 286  		name								string
	 287  		cipherSuites				[]uint16
	 288  		supportedCurves		 []CurveID
	 289  		supportedPoints		 []uint8
	 290  		wantSupportedPoints bool
	 291  	}{
	 292  		{"ECC", []uint16{TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA}, []CurveID{CurveP256}, []uint8{compressionNone}, true},
	 293  		{"RSA", []uint16{TLS_RSA_WITH_AES_256_GCM_SHA384}, nil, nil, false},
	 294  	}
	 295  	for _, tt := range tests {
	 296  		t.Run(tt.name, func(t *testing.T) {
	 297  			clientHello := &clientHelloMsg{
	 298  				vers:							 VersionTLS12,
	 299  				random:						 make([]byte, 32),
	 300  				cipherSuites:			 tt.cipherSuites,
	 301  				compressionMethods: []uint8{compressionNone},
	 302  				supportedCurves:		tt.supportedCurves,
	 303  				supportedPoints:		tt.supportedPoints,
	 304  			}
	 305  
	 306  			c, s := localPipe(t)
	 307  			replyChan := make(chan interface{})
	 308  			go func() {
	 309  				cli := Client(c, testConfig)
	 310  				cli.vers = clientHello.vers
	 311  				cli.writeRecord(recordTypeHandshake, clientHello.marshal())
	 312  				reply, err := cli.readHandshake()
	 313  				c.Close()
	 314  				if err != nil {
	 315  					replyChan <- err
	 316  				} else {
	 317  					replyChan <- reply
	 318  				}
	 319  			}()
	 320  			config := testConfig.Clone()
	 321  			config.CipherSuites = clientHello.cipherSuites
	 322  			Server(s, config).Handshake()
	 323  			s.Close()
	 324  			reply := <-replyChan
	 325  			if err, ok := reply.(error); ok {
	 326  				t.Fatal(err)
	 327  			}
	 328  			serverHello, ok := reply.(*serverHelloMsg)
	 329  			if !ok {
	 330  				t.Fatalf("didn't get ServerHello message in reply. Got %v\n", reply)
	 331  			}
	 332  			if tt.wantSupportedPoints {
	 333  				if len(serverHello.supportedPoints) < 1 {
	 334  					t.Fatal("missing ec_point_format extension from server")
	 335  				}
	 336  				found := false
	 337  				for _, p := range serverHello.supportedPoints {
	 338  					if p == pointFormatUncompressed {
	 339  						found = true
	 340  						break
	 341  					}
	 342  				}
	 343  				if !found {
	 344  					t.Fatal("missing uncompressed format in ec_point_format extension from server")
	 345  				}
	 346  			} else {
	 347  				if len(serverHello.supportedPoints) != 0 {
	 348  					t.Fatalf("unexcpected ec_point_format extension from server: %v", serverHello.supportedPoints)
	 349  				}
	 350  			}
	 351  		})
	 352  	}
	 353  }
	 354  
	 355  func TestAlertForwarding(t *testing.T) {
	 356  	c, s := localPipe(t)
	 357  	go func() {
	 358  		Client(c, testConfig).sendAlert(alertUnknownCA)
	 359  		c.Close()
	 360  	}()
	 361  
	 362  	err := Server(s, testConfig).Handshake()
	 363  	s.Close()
	 364  	var opErr *net.OpError
	 365  	if !errors.As(err, &opErr) || opErr.Err != error(alertUnknownCA) {
	 366  		t.Errorf("Got error: %s; expected: %s", err, error(alertUnknownCA))
	 367  	}
	 368  }
	 369  
	 370  func TestClose(t *testing.T) {
	 371  	c, s := localPipe(t)
	 372  	go c.Close()
	 373  
	 374  	err := Server(s, testConfig).Handshake()
	 375  	s.Close()
	 376  	if err != io.EOF {
	 377  		t.Errorf("Got error: %s; expected: %s", err, io.EOF)
	 378  	}
	 379  }
	 380  
	 381  func TestVersion(t *testing.T) {
	 382  	serverConfig := &Config{
	 383  		Certificates: testConfig.Certificates,
	 384  		MaxVersion:	 VersionTLS11,
	 385  	}
	 386  	clientConfig := &Config{
	 387  		InsecureSkipVerify: true,
	 388  	}
	 389  	state, _, err := testHandshake(t, clientConfig, serverConfig)
	 390  	if err != nil {
	 391  		t.Fatalf("handshake failed: %s", err)
	 392  	}
	 393  	if state.Version != VersionTLS11 {
	 394  		t.Fatalf("Incorrect version %x, should be %x", state.Version, VersionTLS11)
	 395  	}
	 396  }
	 397  
	 398  func TestCipherSuitePreference(t *testing.T) {
	 399  	serverConfig := &Config{
	 400  		CipherSuites: []uint16{TLS_RSA_WITH_RC4_128_SHA, TLS_AES_128_GCM_SHA256,
	 401  			TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256},
	 402  		Certificates: testConfig.Certificates,
	 403  		MaxVersion:	 VersionTLS12,
	 404  		GetConfigForClient: func(chi *ClientHelloInfo) (*Config, error) {
	 405  			if chi.CipherSuites[0] != TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256 {
	 406  				t.Error("the advertised order should not depend on Config.CipherSuites")
	 407  			}
	 408  			if len(chi.CipherSuites) != 2+len(defaultCipherSuitesTLS13) {
	 409  				t.Error("the advertised TLS 1.2 suites should be filtered by Config.CipherSuites")
	 410  			}
	 411  			return nil, nil
	 412  		},
	 413  	}
	 414  	clientConfig := &Config{
	 415  		CipherSuites:			 []uint16{TLS_RSA_WITH_AES_128_CBC_SHA, TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256},
	 416  		InsecureSkipVerify: true,
	 417  	}
	 418  	state, _, err := testHandshake(t, clientConfig, serverConfig)
	 419  	if err != nil {
	 420  		t.Fatalf("handshake failed: %s", err)
	 421  	}
	 422  	if state.CipherSuite != TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256 {
	 423  		t.Error("the preference order should not depend on Config.CipherSuites")
	 424  	}
	 425  }
	 426  
	 427  func TestSCTHandshake(t *testing.T) {
	 428  	t.Run("TLSv12", func(t *testing.T) { testSCTHandshake(t, VersionTLS12) })
	 429  	t.Run("TLSv13", func(t *testing.T) { testSCTHandshake(t, VersionTLS13) })
	 430  }
	 431  
	 432  func testSCTHandshake(t *testing.T, version uint16) {
	 433  	expected := [][]byte{[]byte("certificate"), []byte("transparency")}
	 434  	serverConfig := &Config{
	 435  		Certificates: []Certificate{{
	 436  			Certificate:								 [][]byte{testRSACertificate},
	 437  			PrivateKey:									testRSAPrivateKey,
	 438  			SignedCertificateTimestamps: expected,
	 439  		}},
	 440  		MaxVersion: version,
	 441  	}
	 442  	clientConfig := &Config{
	 443  		InsecureSkipVerify: true,
	 444  	}
	 445  	_, state, err := testHandshake(t, clientConfig, serverConfig)
	 446  	if err != nil {
	 447  		t.Fatalf("handshake failed: %s", err)
	 448  	}
	 449  	actual := state.SignedCertificateTimestamps
	 450  	if len(actual) != len(expected) {
	 451  		t.Fatalf("got %d scts, want %d", len(actual), len(expected))
	 452  	}
	 453  	for i, sct := range expected {
	 454  		if !bytes.Equal(sct, actual[i]) {
	 455  			t.Fatalf("SCT #%d was %x, but expected %x", i, actual[i], sct)
	 456  		}
	 457  	}
	 458  }
	 459  
	 460  func TestCrossVersionResume(t *testing.T) {
	 461  	t.Run("TLSv12", func(t *testing.T) { testCrossVersionResume(t, VersionTLS12) })
	 462  	t.Run("TLSv13", func(t *testing.T) { testCrossVersionResume(t, VersionTLS13) })
	 463  }
	 464  
	 465  func testCrossVersionResume(t *testing.T, version uint16) {
	 466  	serverConfig := &Config{
	 467  		CipherSuites: []uint16{TLS_RSA_WITH_AES_128_CBC_SHA},
	 468  		Certificates: testConfig.Certificates,
	 469  	}
	 470  	clientConfig := &Config{
	 471  		CipherSuites:			 []uint16{TLS_RSA_WITH_AES_128_CBC_SHA},
	 472  		InsecureSkipVerify: true,
	 473  		ClientSessionCache: NewLRUClientSessionCache(1),
	 474  		ServerName:				 "servername",
	 475  	}
	 476  
	 477  	// Establish a session at TLS 1.1.
	 478  	clientConfig.MaxVersion = VersionTLS11
	 479  	_, _, err := testHandshake(t, clientConfig, serverConfig)
	 480  	if err != nil {
	 481  		t.Fatalf("handshake failed: %s", err)
	 482  	}
	 483  
	 484  	// The client session cache now contains a TLS 1.1 session.
	 485  	state, _, err := testHandshake(t, clientConfig, serverConfig)
	 486  	if err != nil {
	 487  		t.Fatalf("handshake failed: %s", err)
	 488  	}
	 489  	if !state.DidResume {
	 490  		t.Fatalf("handshake did not resume at the same version")
	 491  	}
	 492  
	 493  	// Test that the server will decline to resume at a lower version.
	 494  	clientConfig.MaxVersion = VersionTLS10
	 495  	state, _, err = testHandshake(t, clientConfig, serverConfig)
	 496  	if err != nil {
	 497  		t.Fatalf("handshake failed: %s", err)
	 498  	}
	 499  	if state.DidResume {
	 500  		t.Fatalf("handshake resumed at a lower version")
	 501  	}
	 502  
	 503  	// The client session cache now contains a TLS 1.0 session.
	 504  	state, _, err = testHandshake(t, clientConfig, serverConfig)
	 505  	if err != nil {
	 506  		t.Fatalf("handshake failed: %s", err)
	 507  	}
	 508  	if !state.DidResume {
	 509  		t.Fatalf("handshake did not resume at the same version")
	 510  	}
	 511  
	 512  	// Test that the server will decline to resume at a higher version.
	 513  	clientConfig.MaxVersion = VersionTLS11
	 514  	state, _, err = testHandshake(t, clientConfig, serverConfig)
	 515  	if err != nil {
	 516  		t.Fatalf("handshake failed: %s", err)
	 517  	}
	 518  	if state.DidResume {
	 519  		t.Fatalf("handshake resumed at a higher version")
	 520  	}
	 521  }
	 522  
	 523  // Note: see comment in handshake_test.go for details of how the reference
	 524  // tests work.
	 525  
	 526  // serverTest represents a test of the TLS server handshake against a reference
	 527  // implementation.
	 528  type serverTest struct {
	 529  	// name is a freeform string identifying the test and the file in which
	 530  	// the expected results will be stored.
	 531  	name string
	 532  	// command, if not empty, contains a series of arguments for the
	 533  	// command to run for the reference server.
	 534  	command []string
	 535  	// expectedPeerCerts contains a list of PEM blocks of expected
	 536  	// certificates from the client.
	 537  	expectedPeerCerts []string
	 538  	// config, if not nil, contains a custom Config to use for this test.
	 539  	config *Config
	 540  	// expectHandshakeErrorIncluding, when not empty, contains a string
	 541  	// that must be a substring of the error resulting from the handshake.
	 542  	expectHandshakeErrorIncluding string
	 543  	// validate, if not nil, is a function that will be called with the
	 544  	// ConnectionState of the resulting connection. It returns false if the
	 545  	// ConnectionState is unacceptable.
	 546  	validate func(ConnectionState) error
	 547  	// wait, if true, prevents this subtest from calling t.Parallel.
	 548  	// If false, runServerTest* returns immediately.
	 549  	wait bool
	 550  }
	 551  
	 552  var defaultClientCommand = []string{"openssl", "s_client", "-no_ticket"}
	 553  
	 554  // connFromCommand starts opens a listening socket and starts the reference
	 555  // client to connect to it. It returns a recordingConn that wraps the resulting
	 556  // connection.
	 557  func (test *serverTest) connFromCommand() (conn *recordingConn, child *exec.Cmd, err error) {
	 558  	l, err := net.ListenTCP("tcp", &net.TCPAddr{
	 559  		IP:	 net.IPv4(127, 0, 0, 1),
	 560  		Port: 0,
	 561  	})
	 562  	if err != nil {
	 563  		return nil, nil, err
	 564  	}
	 565  	defer l.Close()
	 566  
	 567  	port := l.Addr().(*net.TCPAddr).Port
	 568  
	 569  	var command []string
	 570  	command = append(command, test.command...)
	 571  	if len(command) == 0 {
	 572  		command = defaultClientCommand
	 573  	}
	 574  	command = append(command, "-connect")
	 575  	command = append(command, fmt.Sprintf("127.0.0.1:%d", port))
	 576  	cmd := exec.Command(command[0], command[1:]...)
	 577  	cmd.Stdin = nil
	 578  	var output bytes.Buffer
	 579  	cmd.Stdout = &output
	 580  	cmd.Stderr = &output
	 581  	if err := cmd.Start(); err != nil {
	 582  		return nil, nil, err
	 583  	}
	 584  
	 585  	connChan := make(chan interface{}, 1)
	 586  	go func() {
	 587  		tcpConn, err := l.Accept()
	 588  		if err != nil {
	 589  			connChan <- err
	 590  			return
	 591  		}
	 592  		connChan <- tcpConn
	 593  	}()
	 594  
	 595  	var tcpConn net.Conn
	 596  	select {
	 597  	case connOrError := <-connChan:
	 598  		if err, ok := connOrError.(error); ok {
	 599  			return nil, nil, err
	 600  		}
	 601  		tcpConn = connOrError.(net.Conn)
	 602  	case <-time.After(2 * time.Second):
	 603  		return nil, nil, errors.New("timed out waiting for connection from child process")
	 604  	}
	 605  
	 606  	record := &recordingConn{
	 607  		Conn: tcpConn,
	 608  	}
	 609  
	 610  	return record, cmd, nil
	 611  }
	 612  
	 613  func (test *serverTest) dataPath() string {
	 614  	return filepath.Join("testdata", "Server-"+test.name)
	 615  }
	 616  
	 617  func (test *serverTest) loadData() (flows [][]byte, err error) {
	 618  	in, err := os.Open(test.dataPath())
	 619  	if err != nil {
	 620  		return nil, err
	 621  	}
	 622  	defer in.Close()
	 623  	return parseTestData(in)
	 624  }
	 625  
	 626  func (test *serverTest) run(t *testing.T, write bool) {
	 627  	var clientConn, serverConn net.Conn
	 628  	var recordingConn *recordingConn
	 629  	var childProcess *exec.Cmd
	 630  
	 631  	if write {
	 632  		var err error
	 633  		recordingConn, childProcess, err = test.connFromCommand()
	 634  		if err != nil {
	 635  			t.Fatalf("Failed to start subcommand: %s", err)
	 636  		}
	 637  		serverConn = recordingConn
	 638  		defer func() {
	 639  			if t.Failed() {
	 640  				t.Logf("OpenSSL output:\n\n%s", childProcess.Stdout)
	 641  			}
	 642  		}()
	 643  	} else {
	 644  		clientConn, serverConn = localPipe(t)
	 645  	}
	 646  	config := test.config
	 647  	if config == nil {
	 648  		config = testConfig
	 649  	}
	 650  	server := Server(serverConn, config)
	 651  	connStateChan := make(chan ConnectionState, 1)
	 652  	go func() {
	 653  		_, err := server.Write([]byte("hello, world\n"))
	 654  		if len(test.expectHandshakeErrorIncluding) > 0 {
	 655  			if err == nil {
	 656  				t.Errorf("Error expected, but no error returned")
	 657  			} else if s := err.Error(); !strings.Contains(s, test.expectHandshakeErrorIncluding) {
	 658  				t.Errorf("Error expected containing '%s' but got '%s'", test.expectHandshakeErrorIncluding, s)
	 659  			}
	 660  		} else {
	 661  			if err != nil {
	 662  				t.Logf("Error from Server.Write: '%s'", err)
	 663  			}
	 664  		}
	 665  		server.Close()
	 666  		serverConn.Close()
	 667  		connStateChan <- server.ConnectionState()
	 668  	}()
	 669  
	 670  	if !write {
	 671  		flows, err := test.loadData()
	 672  		if err != nil {
	 673  			t.Fatalf("%s: failed to load data from %s", test.name, test.dataPath())
	 674  		}
	 675  		for i, b := range flows {
	 676  			if i%2 == 0 {
	 677  				if *fast {
	 678  					clientConn.SetWriteDeadline(time.Now().Add(1 * time.Second))
	 679  				} else {
	 680  					clientConn.SetWriteDeadline(time.Now().Add(1 * time.Minute))
	 681  				}
	 682  				clientConn.Write(b)
	 683  				continue
	 684  			}
	 685  			bb := make([]byte, len(b))
	 686  			if *fast {
	 687  				clientConn.SetReadDeadline(time.Now().Add(1 * time.Second))
	 688  			} else {
	 689  				clientConn.SetReadDeadline(time.Now().Add(1 * time.Minute))
	 690  			}
	 691  			n, err := io.ReadFull(clientConn, bb)
	 692  			if err != nil {
	 693  				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)
	 694  			}
	 695  			if !bytes.Equal(b, bb) {
	 696  				t.Fatalf("%s #%d: mismatch on read: got:%x want:%x", test.name, i+1, bb, b)
	 697  			}
	 698  		}
	 699  		clientConn.Close()
	 700  	}
	 701  
	 702  	connState := <-connStateChan
	 703  	peerCerts := connState.PeerCertificates
	 704  	if len(peerCerts) == len(test.expectedPeerCerts) {
	 705  		for i, peerCert := range peerCerts {
	 706  			block, _ := pem.Decode([]byte(test.expectedPeerCerts[i]))
	 707  			if !bytes.Equal(block.Bytes, peerCert.Raw) {
	 708  				t.Fatalf("%s: mismatch on peer cert %d", test.name, i+1)
	 709  			}
	 710  		}
	 711  	} else {
	 712  		t.Fatalf("%s: mismatch on peer list length: %d (wanted) != %d (got)", test.name, len(test.expectedPeerCerts), len(peerCerts))
	 713  	}
	 714  
	 715  	if test.validate != nil {
	 716  		if err := test.validate(connState); err != nil {
	 717  			t.Fatalf("validate callback returned error: %s", err)
	 718  		}
	 719  	}
	 720  
	 721  	if write {
	 722  		path := test.dataPath()
	 723  		out, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644)
	 724  		if err != nil {
	 725  			t.Fatalf("Failed to create output file: %s", err)
	 726  		}
	 727  		defer out.Close()
	 728  		recordingConn.Close()
	 729  		if len(recordingConn.flows) < 3 {
	 730  			if len(test.expectHandshakeErrorIncluding) == 0 {
	 731  				t.Fatalf("Handshake failed")
	 732  			}
	 733  		}
	 734  		recordingConn.WriteTo(out)
	 735  		t.Logf("Wrote %s\n", path)
	 736  		childProcess.Wait()
	 737  	}
	 738  }
	 739  
	 740  func runServerTestForVersion(t *testing.T, template *serverTest, version, option string) {
	 741  	// Make a deep copy of the template before going parallel.
	 742  	test := *template
	 743  	if template.config != nil {
	 744  		test.config = template.config.Clone()
	 745  	}
	 746  	test.name = version + "-" + test.name
	 747  	if len(test.command) == 0 {
	 748  		test.command = defaultClientCommand
	 749  	}
	 750  	test.command = append([]string(nil), test.command...)
	 751  	test.command = append(test.command, option)
	 752  
	 753  	runTestAndUpdateIfNeeded(t, version, test.run, test.wait)
	 754  }
	 755  
	 756  func runServerTestTLS10(t *testing.T, template *serverTest) {
	 757  	runServerTestForVersion(t, template, "TLSv10", "-tls1")
	 758  }
	 759  
	 760  func runServerTestTLS11(t *testing.T, template *serverTest) {
	 761  	runServerTestForVersion(t, template, "TLSv11", "-tls1_1")
	 762  }
	 763  
	 764  func runServerTestTLS12(t *testing.T, template *serverTest) {
	 765  	runServerTestForVersion(t, template, "TLSv12", "-tls1_2")
	 766  }
	 767  
	 768  func runServerTestTLS13(t *testing.T, template *serverTest) {
	 769  	runServerTestForVersion(t, template, "TLSv13", "-tls1_3")
	 770  }
	 771  
	 772  func TestHandshakeServerRSARC4(t *testing.T) {
	 773  	test := &serverTest{
	 774  		name:		"RSA-RC4",
	 775  		command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "RC4-SHA"},
	 776  	}
	 777  	runServerTestTLS10(t, test)
	 778  	runServerTestTLS11(t, test)
	 779  	runServerTestTLS12(t, test)
	 780  }
	 781  
	 782  func TestHandshakeServerRSA3DES(t *testing.T) {
	 783  	test := &serverTest{
	 784  		name:		"RSA-3DES",
	 785  		command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "DES-CBC3-SHA"},
	 786  	}
	 787  	runServerTestTLS10(t, test)
	 788  	runServerTestTLS12(t, test)
	 789  }
	 790  
	 791  func TestHandshakeServerRSAAES(t *testing.T) {
	 792  	test := &serverTest{
	 793  		name:		"RSA-AES",
	 794  		command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "AES128-SHA"},
	 795  	}
	 796  	runServerTestTLS10(t, test)
	 797  	runServerTestTLS12(t, test)
	 798  }
	 799  
	 800  func TestHandshakeServerAESGCM(t *testing.T) {
	 801  	test := &serverTest{
	 802  		name:		"RSA-AES-GCM",
	 803  		command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "ECDHE-RSA-AES128-GCM-SHA256"},
	 804  	}
	 805  	runServerTestTLS12(t, test)
	 806  }
	 807  
	 808  func TestHandshakeServerAES256GCMSHA384(t *testing.T) {
	 809  	test := &serverTest{
	 810  		name:		"RSA-AES256-GCM-SHA384",
	 811  		command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "ECDHE-RSA-AES256-GCM-SHA384"},
	 812  	}
	 813  	runServerTestTLS12(t, test)
	 814  }
	 815  
	 816  func TestHandshakeServerAES128SHA256(t *testing.T) {
	 817  	test := &serverTest{
	 818  		name:		"AES128-SHA256",
	 819  		command: []string{"openssl", "s_client", "-no_ticket", "-ciphersuites", "TLS_AES_128_GCM_SHA256"},
	 820  	}
	 821  	runServerTestTLS13(t, test)
	 822  }
	 823  func TestHandshakeServerAES256SHA384(t *testing.T) {
	 824  	test := &serverTest{
	 825  		name:		"AES256-SHA384",
	 826  		command: []string{"openssl", "s_client", "-no_ticket", "-ciphersuites", "TLS_AES_256_GCM_SHA384"},
	 827  	}
	 828  	runServerTestTLS13(t, test)
	 829  }
	 830  func TestHandshakeServerCHACHA20SHA256(t *testing.T) {
	 831  	test := &serverTest{
	 832  		name:		"CHACHA20-SHA256",
	 833  		command: []string{"openssl", "s_client", "-no_ticket", "-ciphersuites", "TLS_CHACHA20_POLY1305_SHA256"},
	 834  	}
	 835  	runServerTestTLS13(t, test)
	 836  }
	 837  
	 838  func TestHandshakeServerECDHEECDSAAES(t *testing.T) {
	 839  	config := testConfig.Clone()
	 840  	config.Certificates = make([]Certificate, 1)
	 841  	config.Certificates[0].Certificate = [][]byte{testECDSACertificate}
	 842  	config.Certificates[0].PrivateKey = testECDSAPrivateKey
	 843  	config.BuildNameToCertificate()
	 844  
	 845  	test := &serverTest{
	 846  		name:		"ECDHE-ECDSA-AES",
	 847  		command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "ECDHE-ECDSA-AES256-SHA", "-ciphersuites", "TLS_AES_128_GCM_SHA256"},
	 848  		config:	config,
	 849  	}
	 850  	runServerTestTLS10(t, test)
	 851  	runServerTestTLS12(t, test)
	 852  	runServerTestTLS13(t, test)
	 853  }
	 854  
	 855  func TestHandshakeServerX25519(t *testing.T) {
	 856  	config := testConfig.Clone()
	 857  	config.CurvePreferences = []CurveID{X25519}
	 858  
	 859  	test := &serverTest{
	 860  		name:		"X25519",
	 861  		command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "ECDHE-RSA-CHACHA20-POLY1305", "-ciphersuites", "TLS_CHACHA20_POLY1305_SHA256", "-curves", "X25519"},
	 862  		config:	config,
	 863  	}
	 864  	runServerTestTLS12(t, test)
	 865  	runServerTestTLS13(t, test)
	 866  }
	 867  
	 868  func TestHandshakeServerP256(t *testing.T) {
	 869  	config := testConfig.Clone()
	 870  	config.CurvePreferences = []CurveID{CurveP256}
	 871  
	 872  	test := &serverTest{
	 873  		name:		"P256",
	 874  		command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "ECDHE-RSA-CHACHA20-POLY1305", "-ciphersuites", "TLS_CHACHA20_POLY1305_SHA256", "-curves", "P-256"},
	 875  		config:	config,
	 876  	}
	 877  	runServerTestTLS12(t, test)
	 878  	runServerTestTLS13(t, test)
	 879  }
	 880  
	 881  func TestHandshakeServerHelloRetryRequest(t *testing.T) {
	 882  	config := testConfig.Clone()
	 883  	config.CurvePreferences = []CurveID{CurveP256}
	 884  
	 885  	test := &serverTest{
	 886  		name:		"HelloRetryRequest",
	 887  		command: []string{"openssl", "s_client", "-no_ticket", "-ciphersuites", "TLS_CHACHA20_POLY1305_SHA256", "-curves", "X25519:P-256"},
	 888  		config:	config,
	 889  	}
	 890  	runServerTestTLS13(t, test)
	 891  }
	 892  
	 893  func TestHandshakeServerALPN(t *testing.T) {
	 894  	config := testConfig.Clone()
	 895  	config.NextProtos = []string{"proto1", "proto2"}
	 896  
	 897  	test := &serverTest{
	 898  		name: "ALPN",
	 899  		// Note that this needs OpenSSL 1.0.2 because that is the first
	 900  		// version that supports the -alpn flag.
	 901  		command: []string{"openssl", "s_client", "-alpn", "proto2,proto1", "-cipher", "ECDHE-RSA-CHACHA20-POLY1305", "-ciphersuites", "TLS_CHACHA20_POLY1305_SHA256"},
	 902  		config:	config,
	 903  		validate: func(state ConnectionState) error {
	 904  			// The server's preferences should override the client.
	 905  			if state.NegotiatedProtocol != "proto1" {
	 906  				return fmt.Errorf("Got protocol %q, wanted proto1", state.NegotiatedProtocol)
	 907  			}
	 908  			return nil
	 909  		},
	 910  	}
	 911  	runServerTestTLS12(t, test)
	 912  	runServerTestTLS13(t, test)
	 913  }
	 914  
	 915  func TestHandshakeServerALPNNoMatch(t *testing.T) {
	 916  	config := testConfig.Clone()
	 917  	config.NextProtos = []string{"proto3"}
	 918  
	 919  	test := &serverTest{
	 920  		name: "ALPN-NoMatch",
	 921  		// Note that this needs OpenSSL 1.0.2 because that is the first
	 922  		// version that supports the -alpn flag.
	 923  		command:											 []string{"openssl", "s_client", "-alpn", "proto2,proto1", "-cipher", "ECDHE-RSA-CHACHA20-POLY1305", "-ciphersuites", "TLS_CHACHA20_POLY1305_SHA256"},
	 924  		config:												config,
	 925  		expectHandshakeErrorIncluding: "client requested unsupported application protocol",
	 926  	}
	 927  	runServerTestTLS12(t, test)
	 928  	runServerTestTLS13(t, test)
	 929  }
	 930  
	 931  func TestHandshakeServerALPNNotConfigured(t *testing.T) {
	 932  	config := testConfig.Clone()
	 933  	config.NextProtos = nil
	 934  
	 935  	test := &serverTest{
	 936  		name: "ALPN-NotConfigured",
	 937  		// Note that this needs OpenSSL 1.0.2 because that is the first
	 938  		// version that supports the -alpn flag.
	 939  		command: []string{"openssl", "s_client", "-alpn", "proto2,proto1", "-cipher", "ECDHE-RSA-CHACHA20-POLY1305", "-ciphersuites", "TLS_CHACHA20_POLY1305_SHA256"},
	 940  		config:	config,
	 941  		validate: func(state ConnectionState) error {
	 942  			if state.NegotiatedProtocol != "" {
	 943  				return fmt.Errorf("Got protocol %q, wanted nothing", state.NegotiatedProtocol)
	 944  			}
	 945  			return nil
	 946  		},
	 947  	}
	 948  	runServerTestTLS12(t, test)
	 949  	runServerTestTLS13(t, test)
	 950  }
	 951  
	 952  func TestHandshakeServerALPNFallback(t *testing.T) {
	 953  	config := testConfig.Clone()
	 954  	config.NextProtos = []string{"proto1", "h2", "proto2"}
	 955  
	 956  	test := &serverTest{
	 957  		name: "ALPN-Fallback",
	 958  		// Note that this needs OpenSSL 1.0.2 because that is the first
	 959  		// version that supports the -alpn flag.
	 960  		command: []string{"openssl", "s_client", "-alpn", "proto3,http/1.1,proto4", "-cipher", "ECDHE-RSA-CHACHA20-POLY1305", "-ciphersuites", "TLS_CHACHA20_POLY1305_SHA256"},
	 961  		config:	config,
	 962  		validate: func(state ConnectionState) error {
	 963  			if state.NegotiatedProtocol != "" {
	 964  				return fmt.Errorf("Got protocol %q, wanted nothing", state.NegotiatedProtocol)
	 965  			}
	 966  			return nil
	 967  		},
	 968  	}
	 969  	runServerTestTLS12(t, test)
	 970  	runServerTestTLS13(t, test)
	 971  }
	 972  
	 973  // TestHandshakeServerSNI involves a client sending an SNI extension of
	 974  // "snitest.com", which happens to match the CN of testSNICertificate. The test
	 975  // verifies that the server correctly selects that certificate.
	 976  func TestHandshakeServerSNI(t *testing.T) {
	 977  	test := &serverTest{
	 978  		name:		"SNI",
	 979  		command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "AES128-SHA", "-servername", "snitest.com"},
	 980  	}
	 981  	runServerTestTLS12(t, test)
	 982  }
	 983  
	 984  // TestHandshakeServerSNICertForName is similar to TestHandshakeServerSNI, but
	 985  // tests the dynamic GetCertificate method
	 986  func TestHandshakeServerSNIGetCertificate(t *testing.T) {
	 987  	config := testConfig.Clone()
	 988  
	 989  	// Replace the NameToCertificate map with a GetCertificate function
	 990  	nameToCert := config.NameToCertificate
	 991  	config.NameToCertificate = nil
	 992  	config.GetCertificate = func(clientHello *ClientHelloInfo) (*Certificate, error) {
	 993  		cert := nameToCert[clientHello.ServerName]
	 994  		return cert, nil
	 995  	}
	 996  	test := &serverTest{
	 997  		name:		"SNI-GetCertificate",
	 998  		command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "AES128-SHA", "-servername", "snitest.com"},
	 999  		config:	config,
	1000  	}
	1001  	runServerTestTLS12(t, test)
	1002  }
	1003  
	1004  // TestHandshakeServerSNICertForNameNotFound is similar to
	1005  // TestHandshakeServerSNICertForName, but tests to make sure that when the
	1006  // GetCertificate method doesn't return a cert, we fall back to what's in
	1007  // the NameToCertificate map.
	1008  func TestHandshakeServerSNIGetCertificateNotFound(t *testing.T) {
	1009  	config := testConfig.Clone()
	1010  
	1011  	config.GetCertificate = func(clientHello *ClientHelloInfo) (*Certificate, error) {
	1012  		return nil, nil
	1013  	}
	1014  	test := &serverTest{
	1015  		name:		"SNI-GetCertificateNotFound",
	1016  		command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "AES128-SHA", "-servername", "snitest.com"},
	1017  		config:	config,
	1018  	}
	1019  	runServerTestTLS12(t, test)
	1020  }
	1021  
	1022  // TestHandshakeServerSNICertForNameError tests to make sure that errors in
	1023  // GetCertificate result in a tls alert.
	1024  func TestHandshakeServerSNIGetCertificateError(t *testing.T) {
	1025  	const errMsg = "TestHandshakeServerSNIGetCertificateError error"
	1026  
	1027  	serverConfig := testConfig.Clone()
	1028  	serverConfig.GetCertificate = func(clientHello *ClientHelloInfo) (*Certificate, error) {
	1029  		return nil, errors.New(errMsg)
	1030  	}
	1031  
	1032  	clientHello := &clientHelloMsg{
	1033  		vers:							 VersionTLS10,
	1034  		random:						 make([]byte, 32),
	1035  		cipherSuites:			 []uint16{TLS_RSA_WITH_RC4_128_SHA},
	1036  		compressionMethods: []uint8{compressionNone},
	1037  		serverName:				 "test",
	1038  	}
	1039  	testClientHelloFailure(t, serverConfig, clientHello, errMsg)
	1040  }
	1041  
	1042  // TestHandshakeServerEmptyCertificates tests that GetCertificates is called in
	1043  // the case that Certificates is empty, even without SNI.
	1044  func TestHandshakeServerEmptyCertificates(t *testing.T) {
	1045  	const errMsg = "TestHandshakeServerEmptyCertificates error"
	1046  
	1047  	serverConfig := testConfig.Clone()
	1048  	serverConfig.GetCertificate = func(clientHello *ClientHelloInfo) (*Certificate, error) {
	1049  		return nil, errors.New(errMsg)
	1050  	}
	1051  	serverConfig.Certificates = nil
	1052  
	1053  	clientHello := &clientHelloMsg{
	1054  		vers:							 VersionTLS10,
	1055  		random:						 make([]byte, 32),
	1056  		cipherSuites:			 []uint16{TLS_RSA_WITH_RC4_128_SHA},
	1057  		compressionMethods: []uint8{compressionNone},
	1058  	}
	1059  	testClientHelloFailure(t, serverConfig, clientHello, errMsg)
	1060  
	1061  	// With an empty Certificates and a nil GetCertificate, the server
	1062  	// should always return a “no certificates” error.
	1063  	serverConfig.GetCertificate = nil
	1064  
	1065  	clientHello = &clientHelloMsg{
	1066  		vers:							 VersionTLS10,
	1067  		random:						 make([]byte, 32),
	1068  		cipherSuites:			 []uint16{TLS_RSA_WITH_RC4_128_SHA},
	1069  		compressionMethods: []uint8{compressionNone},
	1070  	}
	1071  	testClientHelloFailure(t, serverConfig, clientHello, "no certificates")
	1072  }
	1073  
	1074  func TestServerResumption(t *testing.T) {
	1075  	sessionFilePath := tempFile("")
	1076  	defer os.Remove(sessionFilePath)
	1077  
	1078  	testIssue := &serverTest{
	1079  		name:		"IssueTicket",
	1080  		command: []string{"openssl", "s_client", "-cipher", "AES128-SHA", "-ciphersuites", "TLS_AES_128_GCM_SHA256", "-sess_out", sessionFilePath},
	1081  		wait:		true,
	1082  	}
	1083  	testResume := &serverTest{
	1084  		name:		"Resume",
	1085  		command: []string{"openssl", "s_client", "-cipher", "AES128-SHA", "-ciphersuites", "TLS_AES_128_GCM_SHA256", "-sess_in", sessionFilePath},
	1086  		validate: func(state ConnectionState) error {
	1087  			if !state.DidResume {
	1088  				return errors.New("did not resume")
	1089  			}
	1090  			return nil
	1091  		},
	1092  	}
	1093  
	1094  	runServerTestTLS12(t, testIssue)
	1095  	runServerTestTLS12(t, testResume)
	1096  
	1097  	runServerTestTLS13(t, testIssue)
	1098  	runServerTestTLS13(t, testResume)
	1099  
	1100  	config := testConfig.Clone()
	1101  	config.CurvePreferences = []CurveID{CurveP256}
	1102  
	1103  	testResumeHRR := &serverTest{
	1104  		name: "Resume-HelloRetryRequest",
	1105  		command: []string{"openssl", "s_client", "-curves", "X25519:P-256", "-cipher", "AES128-SHA", "-ciphersuites",
	1106  			"TLS_AES_128_GCM_SHA256", "-sess_in", sessionFilePath},
	1107  		config: config,
	1108  		validate: func(state ConnectionState) error {
	1109  			if !state.DidResume {
	1110  				return errors.New("did not resume")
	1111  			}
	1112  			return nil
	1113  		},
	1114  	}
	1115  
	1116  	runServerTestTLS13(t, testResumeHRR)
	1117  }
	1118  
	1119  func TestServerResumptionDisabled(t *testing.T) {
	1120  	sessionFilePath := tempFile("")
	1121  	defer os.Remove(sessionFilePath)
	1122  
	1123  	config := testConfig.Clone()
	1124  
	1125  	testIssue := &serverTest{
	1126  		name:		"IssueTicketPreDisable",
	1127  		command: []string{"openssl", "s_client", "-cipher", "AES128-SHA", "-ciphersuites", "TLS_AES_128_GCM_SHA256", "-sess_out", sessionFilePath},
	1128  		config:	config,
	1129  		wait:		true,
	1130  	}
	1131  	testResume := &serverTest{
	1132  		name:		"ResumeDisabled",
	1133  		command: []string{"openssl", "s_client", "-cipher", "AES128-SHA", "-ciphersuites", "TLS_AES_128_GCM_SHA256", "-sess_in", sessionFilePath},
	1134  		config:	config,
	1135  		validate: func(state ConnectionState) error {
	1136  			if state.DidResume {
	1137  				return errors.New("resumed with SessionTicketsDisabled")
	1138  			}
	1139  			return nil
	1140  		},
	1141  	}
	1142  
	1143  	config.SessionTicketsDisabled = false
	1144  	runServerTestTLS12(t, testIssue)
	1145  	config.SessionTicketsDisabled = true
	1146  	runServerTestTLS12(t, testResume)
	1147  
	1148  	config.SessionTicketsDisabled = false
	1149  	runServerTestTLS13(t, testIssue)
	1150  	config.SessionTicketsDisabled = true
	1151  	runServerTestTLS13(t, testResume)
	1152  }
	1153  
	1154  func TestFallbackSCSV(t *testing.T) {
	1155  	serverConfig := Config{
	1156  		Certificates: testConfig.Certificates,
	1157  	}
	1158  	test := &serverTest{
	1159  		name:	 "FallbackSCSV",
	1160  		config: &serverConfig,
	1161  		// OpenSSL 1.0.1j is needed for the -fallback_scsv option.
	1162  		command:											 []string{"openssl", "s_client", "-fallback_scsv"},
	1163  		expectHandshakeErrorIncluding: "inappropriate protocol fallback",
	1164  	}
	1165  	runServerTestTLS11(t, test)
	1166  }
	1167  
	1168  func TestHandshakeServerExportKeyingMaterial(t *testing.T) {
	1169  	test := &serverTest{
	1170  		name:		"ExportKeyingMaterial",
	1171  		command: []string{"openssl", "s_client", "-cipher", "ECDHE-RSA-AES256-SHA", "-ciphersuites", "TLS_CHACHA20_POLY1305_SHA256"},
	1172  		config:	testConfig.Clone(),
	1173  		validate: func(state ConnectionState) error {
	1174  			if km, err := state.ExportKeyingMaterial("test", nil, 42); err != nil {
	1175  				return fmt.Errorf("ExportKeyingMaterial failed: %v", err)
	1176  			} else if len(km) != 42 {
	1177  				return fmt.Errorf("Got %d bytes from ExportKeyingMaterial, wanted %d", len(km), 42)
	1178  			}
	1179  			return nil
	1180  		},
	1181  	}
	1182  	runServerTestTLS10(t, test)
	1183  	runServerTestTLS12(t, test)
	1184  	runServerTestTLS13(t, test)
	1185  }
	1186  
	1187  func TestHandshakeServerRSAPKCS1v15(t *testing.T) {
	1188  	test := &serverTest{
	1189  		name:		"RSA-RSAPKCS1v15",
	1190  		command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "ECDHE-RSA-CHACHA20-POLY1305", "-sigalgs", "rsa_pkcs1_sha256"},
	1191  	}
	1192  	runServerTestTLS12(t, test)
	1193  }
	1194  
	1195  func TestHandshakeServerRSAPSS(t *testing.T) {
	1196  	// We send rsa_pss_rsae_sha512 first, as the test key won't fit, and we
	1197  	// verify the server implementation will disregard the client preference in
	1198  	// that case. See Issue 29793.
	1199  	test := &serverTest{
	1200  		name:		"RSA-RSAPSS",
	1201  		command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "ECDHE-RSA-CHACHA20-POLY1305", "-ciphersuites", "TLS_CHACHA20_POLY1305_SHA256", "-sigalgs", "rsa_pss_rsae_sha512:rsa_pss_rsae_sha256"},
	1202  	}
	1203  	runServerTestTLS12(t, test)
	1204  	runServerTestTLS13(t, test)
	1205  
	1206  	test = &serverTest{
	1207  		name:													"RSA-RSAPSS-TooSmall",
	1208  		command:											 []string{"openssl", "s_client", "-no_ticket", "-ciphersuites", "TLS_CHACHA20_POLY1305_SHA256", "-sigalgs", "rsa_pss_rsae_sha512"},
	1209  		expectHandshakeErrorIncluding: "peer doesn't support any of the certificate's signature algorithms",
	1210  	}
	1211  	runServerTestTLS13(t, test)
	1212  }
	1213  
	1214  func TestHandshakeServerEd25519(t *testing.T) {
	1215  	config := testConfig.Clone()
	1216  	config.Certificates = make([]Certificate, 1)
	1217  	config.Certificates[0].Certificate = [][]byte{testEd25519Certificate}
	1218  	config.Certificates[0].PrivateKey = testEd25519PrivateKey
	1219  	config.BuildNameToCertificate()
	1220  
	1221  	test := &serverTest{
	1222  		name:		"Ed25519",
	1223  		command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "ECDHE-ECDSA-CHACHA20-POLY1305", "-ciphersuites", "TLS_CHACHA20_POLY1305_SHA256"},
	1224  		config:	config,
	1225  	}
	1226  	runServerTestTLS12(t, test)
	1227  	runServerTestTLS13(t, test)
	1228  }
	1229  
	1230  func benchmarkHandshakeServer(b *testing.B, version uint16, cipherSuite uint16, curve CurveID, cert []byte, key crypto.PrivateKey) {
	1231  	config := testConfig.Clone()
	1232  	config.CipherSuites = []uint16{cipherSuite}
	1233  	config.CurvePreferences = []CurveID{curve}
	1234  	config.Certificates = make([]Certificate, 1)
	1235  	config.Certificates[0].Certificate = [][]byte{cert}
	1236  	config.Certificates[0].PrivateKey = key
	1237  	config.BuildNameToCertificate()
	1238  
	1239  	clientConn, serverConn := localPipe(b)
	1240  	serverConn = &recordingConn{Conn: serverConn}
	1241  	go func() {
	1242  		config := testConfig.Clone()
	1243  		config.MaxVersion = version
	1244  		config.CurvePreferences = []CurveID{curve}
	1245  		client := Client(clientConn, config)
	1246  		client.Handshake()
	1247  	}()
	1248  	server := Server(serverConn, config)
	1249  	if err := server.Handshake(); err != nil {
	1250  		b.Fatalf("handshake failed: %v", err)
	1251  	}
	1252  	serverConn.Close()
	1253  	flows := serverConn.(*recordingConn).flows
	1254  
	1255  	feeder := make(chan struct{})
	1256  	clientConn, serverConn = localPipe(b)
	1257  
	1258  	go func() {
	1259  		for range feeder {
	1260  			for i, f := range flows {
	1261  				if i%2 == 0 {
	1262  					clientConn.Write(f)
	1263  					continue
	1264  				}
	1265  				ff := make([]byte, len(f))
	1266  				n, err := io.ReadFull(clientConn, ff)
	1267  				if err != nil {
	1268  					b.Errorf("#%d: %s\nRead %d, wanted %d, got %x, wanted %x\n", i+1, err, n, len(ff), ff[:n], f)
	1269  				}
	1270  				if !bytes.Equal(f, ff) {
	1271  					b.Errorf("#%d: mismatch on read: got:%x want:%x", i+1, ff, f)
	1272  				}
	1273  			}
	1274  		}
	1275  	}()
	1276  
	1277  	b.ResetTimer()
	1278  	for i := 0; i < b.N; i++ {
	1279  		feeder <- struct{}{}
	1280  		server := Server(serverConn, config)
	1281  		if err := server.Handshake(); err != nil {
	1282  			b.Fatalf("handshake failed: %v", err)
	1283  		}
	1284  	}
	1285  	close(feeder)
	1286  }
	1287  
	1288  func BenchmarkHandshakeServer(b *testing.B) {
	1289  	b.Run("RSA", func(b *testing.B) {
	1290  		benchmarkHandshakeServer(b, VersionTLS12, TLS_RSA_WITH_AES_128_GCM_SHA256,
	1291  			0, testRSACertificate, testRSAPrivateKey)
	1292  	})
	1293  	b.Run("ECDHE-P256-RSA", func(b *testing.B) {
	1294  		b.Run("TLSv13", func(b *testing.B) {
	1295  			benchmarkHandshakeServer(b, VersionTLS13, TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305,
	1296  				CurveP256, testRSACertificate, testRSAPrivateKey)
	1297  		})
	1298  		b.Run("TLSv12", func(b *testing.B) {
	1299  			benchmarkHandshakeServer(b, VersionTLS12, TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305,
	1300  				CurveP256, testRSACertificate, testRSAPrivateKey)
	1301  		})
	1302  	})
	1303  	b.Run("ECDHE-P256-ECDSA-P256", func(b *testing.B) {
	1304  		b.Run("TLSv13", func(b *testing.B) {
	1305  			benchmarkHandshakeServer(b, VersionTLS13, TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305,
	1306  				CurveP256, testP256Certificate, testP256PrivateKey)
	1307  		})
	1308  		b.Run("TLSv12", func(b *testing.B) {
	1309  			benchmarkHandshakeServer(b, VersionTLS12, TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305,
	1310  				CurveP256, testP256Certificate, testP256PrivateKey)
	1311  		})
	1312  	})
	1313  	b.Run("ECDHE-X25519-ECDSA-P256", func(b *testing.B) {
	1314  		b.Run("TLSv13", func(b *testing.B) {
	1315  			benchmarkHandshakeServer(b, VersionTLS13, TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305,
	1316  				X25519, testP256Certificate, testP256PrivateKey)
	1317  		})
	1318  		b.Run("TLSv12", func(b *testing.B) {
	1319  			benchmarkHandshakeServer(b, VersionTLS12, TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305,
	1320  				X25519, testP256Certificate, testP256PrivateKey)
	1321  		})
	1322  	})
	1323  	b.Run("ECDHE-P521-ECDSA-P521", func(b *testing.B) {
	1324  		if testECDSAPrivateKey.PublicKey.Curve != elliptic.P521() {
	1325  			b.Fatal("test ECDSA key doesn't use curve P-521")
	1326  		}
	1327  		b.Run("TLSv13", func(b *testing.B) {
	1328  			benchmarkHandshakeServer(b, VersionTLS13, TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305,
	1329  				CurveP521, testECDSACertificate, testECDSAPrivateKey)
	1330  		})
	1331  		b.Run("TLSv12", func(b *testing.B) {
	1332  			benchmarkHandshakeServer(b, VersionTLS12, TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305,
	1333  				CurveP521, testECDSACertificate, testECDSAPrivateKey)
	1334  		})
	1335  	})
	1336  }
	1337  
	1338  func TestClientAuth(t *testing.T) {
	1339  	var certPath, keyPath, ecdsaCertPath, ecdsaKeyPath, ed25519CertPath, ed25519KeyPath string
	1340  
	1341  	if *update {
	1342  		certPath = tempFile(clientCertificatePEM)
	1343  		defer os.Remove(certPath)
	1344  		keyPath = tempFile(clientKeyPEM)
	1345  		defer os.Remove(keyPath)
	1346  		ecdsaCertPath = tempFile(clientECDSACertificatePEM)
	1347  		defer os.Remove(ecdsaCertPath)
	1348  		ecdsaKeyPath = tempFile(clientECDSAKeyPEM)
	1349  		defer os.Remove(ecdsaKeyPath)
	1350  		ed25519CertPath = tempFile(clientEd25519CertificatePEM)
	1351  		defer os.Remove(ed25519CertPath)
	1352  		ed25519KeyPath = tempFile(clientEd25519KeyPEM)
	1353  		defer os.Remove(ed25519KeyPath)
	1354  	} else {
	1355  		t.Parallel()
	1356  	}
	1357  
	1358  	config := testConfig.Clone()
	1359  	config.ClientAuth = RequestClientCert
	1360  
	1361  	test := &serverTest{
	1362  		name:		"ClientAuthRequestedNotGiven",
	1363  		command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "AES128-SHA", "-ciphersuites", "TLS_AES_128_GCM_SHA256"},
	1364  		config:	config,
	1365  	}
	1366  	runServerTestTLS12(t, test)
	1367  	runServerTestTLS13(t, test)
	1368  
	1369  	test = &serverTest{
	1370  		name: "ClientAuthRequestedAndGiven",
	1371  		command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "AES128-SHA", "-ciphersuites", "TLS_AES_128_GCM_SHA256",
	1372  			"-cert", certPath, "-key", keyPath, "-client_sigalgs", "rsa_pss_rsae_sha256"},
	1373  		config:						config,
	1374  		expectedPeerCerts: []string{clientCertificatePEM},
	1375  	}
	1376  	runServerTestTLS12(t, test)
	1377  	runServerTestTLS13(t, test)
	1378  
	1379  	test = &serverTest{
	1380  		name: "ClientAuthRequestedAndECDSAGiven",
	1381  		command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "AES128-SHA", "-ciphersuites", "TLS_AES_128_GCM_SHA256",
	1382  			"-cert", ecdsaCertPath, "-key", ecdsaKeyPath},
	1383  		config:						config,
	1384  		expectedPeerCerts: []string{clientECDSACertificatePEM},
	1385  	}
	1386  	runServerTestTLS12(t, test)
	1387  	runServerTestTLS13(t, test)
	1388  
	1389  	test = &serverTest{
	1390  		name: "ClientAuthRequestedAndEd25519Given",
	1391  		command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "AES128-SHA", "-ciphersuites", "TLS_AES_128_GCM_SHA256",
	1392  			"-cert", ed25519CertPath, "-key", ed25519KeyPath},
	1393  		config:						config,
	1394  		expectedPeerCerts: []string{clientEd25519CertificatePEM},
	1395  	}
	1396  	runServerTestTLS12(t, test)
	1397  	runServerTestTLS13(t, test)
	1398  
	1399  	test = &serverTest{
	1400  		name: "ClientAuthRequestedAndPKCS1v15Given",
	1401  		command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "AES128-SHA",
	1402  			"-cert", certPath, "-key", keyPath, "-client_sigalgs", "rsa_pkcs1_sha256"},
	1403  		config:						config,
	1404  		expectedPeerCerts: []string{clientCertificatePEM},
	1405  	}
	1406  	runServerTestTLS12(t, test)
	1407  }
	1408  
	1409  func TestSNIGivenOnFailure(t *testing.T) {
	1410  	const expectedServerName = "test.testing"
	1411  
	1412  	clientHello := &clientHelloMsg{
	1413  		vers:							 VersionTLS10,
	1414  		random:						 make([]byte, 32),
	1415  		cipherSuites:			 []uint16{TLS_RSA_WITH_RC4_128_SHA},
	1416  		compressionMethods: []uint8{compressionNone},
	1417  		serverName:				 expectedServerName,
	1418  	}
	1419  
	1420  	serverConfig := testConfig.Clone()
	1421  	// Erase the server's cipher suites to ensure the handshake fails.
	1422  	serverConfig.CipherSuites = nil
	1423  
	1424  	c, s := localPipe(t)
	1425  	go func() {
	1426  		cli := Client(c, testConfig)
	1427  		cli.vers = clientHello.vers
	1428  		cli.writeRecord(recordTypeHandshake, clientHello.marshal())
	1429  		c.Close()
	1430  	}()
	1431  	conn := Server(s, serverConfig)
	1432  	ctx := context.Background()
	1433  	ch, err := conn.readClientHello(ctx)
	1434  	hs := serverHandshakeState{
	1435  		c:					 conn,
	1436  		ctx:				 ctx,
	1437  		clientHello: ch,
	1438  	}
	1439  	if err == nil {
	1440  		err = hs.processClientHello()
	1441  	}
	1442  	if err == nil {
	1443  		err = hs.pickCipherSuite()
	1444  	}
	1445  	defer s.Close()
	1446  
	1447  	if err == nil {
	1448  		t.Error("No error reported from server")
	1449  	}
	1450  
	1451  	cs := hs.c.ConnectionState()
	1452  	if cs.HandshakeComplete {
	1453  		t.Error("Handshake registered as complete")
	1454  	}
	1455  
	1456  	if cs.ServerName != expectedServerName {
	1457  		t.Errorf("Expected ServerName of %q, but got %q", expectedServerName, cs.ServerName)
	1458  	}
	1459  }
	1460  
	1461  var getConfigForClientTests = []struct {
	1462  	setup					func(config *Config)
	1463  	callback			 func(clientHello *ClientHelloInfo) (*Config, error)
	1464  	errorSubstring string
	1465  	verify				 func(config *Config) error
	1466  }{
	1467  	{
	1468  		nil,
	1469  		func(clientHello *ClientHelloInfo) (*Config, error) {
	1470  			return nil, nil
	1471  		},
	1472  		"",
	1473  		nil,
	1474  	},
	1475  	{
	1476  		nil,
	1477  		func(clientHello *ClientHelloInfo) (*Config, error) {
	1478  			return nil, errors.New("should bubble up")
	1479  		},
	1480  		"should bubble up",
	1481  		nil,
	1482  	},
	1483  	{
	1484  		nil,
	1485  		func(clientHello *ClientHelloInfo) (*Config, error) {
	1486  			config := testConfig.Clone()
	1487  			// Setting a maximum version of TLS 1.1 should cause
	1488  			// the handshake to fail, as the client MinVersion is TLS 1.2.
	1489  			config.MaxVersion = VersionTLS11
	1490  			return config, nil
	1491  		},
	1492  		"client offered only unsupported versions",
	1493  		nil,
	1494  	},
	1495  	{
	1496  		func(config *Config) {
	1497  			for i := range config.SessionTicketKey {
	1498  				config.SessionTicketKey[i] = byte(i)
	1499  			}
	1500  			config.sessionTicketKeys = nil
	1501  		},
	1502  		func(clientHello *ClientHelloInfo) (*Config, error) {
	1503  			config := testConfig.Clone()
	1504  			for i := range config.SessionTicketKey {
	1505  				config.SessionTicketKey[i] = 0
	1506  			}
	1507  			config.sessionTicketKeys = nil
	1508  			return config, nil
	1509  		},
	1510  		"",
	1511  		func(config *Config) error {
	1512  			if config.SessionTicketKey == [32]byte{} {
	1513  				return fmt.Errorf("expected SessionTicketKey to be set")
	1514  			}
	1515  			return nil
	1516  		},
	1517  	},
	1518  	{
	1519  		func(config *Config) {
	1520  			var dummyKey [32]byte
	1521  			for i := range dummyKey {
	1522  				dummyKey[i] = byte(i)
	1523  			}
	1524  
	1525  			config.SetSessionTicketKeys([][32]byte{dummyKey})
	1526  		},
	1527  		func(clientHello *ClientHelloInfo) (*Config, error) {
	1528  			config := testConfig.Clone()
	1529  			config.sessionTicketKeys = nil
	1530  			return config, nil
	1531  		},
	1532  		"",
	1533  		func(config *Config) error {
	1534  			if config.SessionTicketKey == [32]byte{} {
	1535  				return fmt.Errorf("expected SessionTicketKey to be set")
	1536  			}
	1537  			return nil
	1538  		},
	1539  	},
	1540  }
	1541  
	1542  func TestGetConfigForClient(t *testing.T) {
	1543  	serverConfig := testConfig.Clone()
	1544  	clientConfig := testConfig.Clone()
	1545  	clientConfig.MinVersion = VersionTLS12
	1546  
	1547  	for i, test := range getConfigForClientTests {
	1548  		if test.setup != nil {
	1549  			test.setup(serverConfig)
	1550  		}
	1551  
	1552  		var configReturned *Config
	1553  		serverConfig.GetConfigForClient = func(clientHello *ClientHelloInfo) (*Config, error) {
	1554  			config, err := test.callback(clientHello)
	1555  			configReturned = config
	1556  			return config, err
	1557  		}
	1558  		c, s := localPipe(t)
	1559  		done := make(chan error)
	1560  
	1561  		go func() {
	1562  			defer s.Close()
	1563  			done <- Server(s, serverConfig).Handshake()
	1564  		}()
	1565  
	1566  		clientErr := Client(c, clientConfig).Handshake()
	1567  		c.Close()
	1568  
	1569  		serverErr := <-done
	1570  
	1571  		if len(test.errorSubstring) == 0 {
	1572  			if serverErr != nil || clientErr != nil {
	1573  				t.Errorf("test[%d]: expected no error but got serverErr: %q, clientErr: %q", i, serverErr, clientErr)
	1574  			}
	1575  			if test.verify != nil {
	1576  				if err := test.verify(configReturned); err != nil {
	1577  					t.Errorf("test[%d]: verify returned error: %v", i, err)
	1578  				}
	1579  			}
	1580  		} else {
	1581  			if serverErr == nil {
	1582  				t.Errorf("test[%d]: expected error containing %q but got no error", i, test.errorSubstring)
	1583  			} else if !strings.Contains(serverErr.Error(), test.errorSubstring) {
	1584  				t.Errorf("test[%d]: expected error to contain %q but it was %q", i, test.errorSubstring, serverErr)
	1585  			}
	1586  		}
	1587  	}
	1588  }
	1589  
	1590  func TestCloseServerConnectionOnIdleClient(t *testing.T) {
	1591  	clientConn, serverConn := localPipe(t)
	1592  	server := Server(serverConn, testConfig.Clone())
	1593  	go func() {
	1594  		clientConn.Write([]byte{'0'})
	1595  		server.Close()
	1596  	}()
	1597  	server.SetReadDeadline(time.Now().Add(time.Minute))
	1598  	err := server.Handshake()
	1599  	if err != nil {
	1600  		if err, ok := err.(net.Error); ok && err.Timeout() {
	1601  			t.Errorf("Expected a closed network connection error but got '%s'", err.Error())
	1602  		}
	1603  	} else {
	1604  		t.Errorf("Error expected, but no error returned")
	1605  	}
	1606  }
	1607  
	1608  func TestCloneHash(t *testing.T) {
	1609  	h1 := crypto.SHA256.New()
	1610  	h1.Write([]byte("test"))
	1611  	s1 := h1.Sum(nil)
	1612  	h2 := cloneHash(h1, crypto.SHA256)
	1613  	s2 := h2.Sum(nil)
	1614  	if !bytes.Equal(s1, s2) {
	1615  		t.Error("cloned hash generated a different sum")
	1616  	}
	1617  }
	1618  
	1619  func expectError(t *testing.T, err error, sub string) {
	1620  	if err == nil {
	1621  		t.Errorf(`expected error %q, got nil`, sub)
	1622  	} else if !strings.Contains(err.Error(), sub) {
	1623  		t.Errorf(`expected error %q, got %q`, sub, err)
	1624  	}
	1625  }
	1626  
	1627  func TestKeyTooSmallForRSAPSS(t *testing.T) {
	1628  	cert, err := X509KeyPair([]byte(`-----BEGIN CERTIFICATE-----
	1629  MIIBcTCCARugAwIBAgIQGjQnkCFlUqaFlt6ixyz/tDANBgkqhkiG9w0BAQsFADAS
	1630  MRAwDgYDVQQKEwdBY21lIENvMB4XDTE5MDExODIzMjMyOFoXDTIwMDExODIzMjMy
	1631  OFowEjEQMA4GA1UEChMHQWNtZSBDbzBcMA0GCSqGSIb3DQEBAQUAA0sAMEgCQQDd
	1632  ez1rFUDwax2HTxbcnFUP9AhcgEGMHVV2nn4VVEWFJB6I8C/Nkx0XyyQlrmFYBzEQ
	1633  nIPhKls4T0hFoLvjJnXpAgMBAAGjTTBLMA4GA1UdDwEB/wQEAwIFoDATBgNVHSUE
	1634  DDAKBggrBgEFBQcDATAMBgNVHRMBAf8EAjAAMBYGA1UdEQQPMA2CC2V4YW1wbGUu
	1635  Y29tMA0GCSqGSIb3DQEBCwUAA0EAxDuUS+BrrS3c+h+k+fQPOmOScy6yTX9mHw0Q
	1636  KbucGamXYEy0URIwOdO0tQ3LHPc1YGvYSPwkDjkjqECs2Vm/AA==
	1637  -----END CERTIFICATE-----`), []byte(testingKey(`-----BEGIN RSA TESTING KEY-----
	1638  MIIBOgIBAAJBAN17PWsVQPBrHYdPFtycVQ/0CFyAQYwdVXaefhVURYUkHojwL82T
	1639  HRfLJCWuYVgHMRCcg+EqWzhPSEWgu+MmdekCAwEAAQJBALjQYNTdXF4CFBbXwUz/
	1640  yt9QFDYT9B5WT/12jeGAe653gtYS6OOi/+eAkGmzg1GlRnw6fOfn+HYNFDORST7z
	1641  4j0CIQDn2xz9hVWQEu9ee3vecNT3f60huDGTNoRhtqgweQGX0wIhAPSLj1VcRZEz
	1642  nKpbtU22+PbIMSJ+e80fmY9LIPx5N4HTAiAthGSimMR9bloz0EY3GyuUEyqoDgMd
	1643  hXxjuno2WesoJQIgemilbcALXpxsLmZLgcQ2KSmaVr7jb5ECx9R+hYKTw1sCIG4s
	1644  T+E0J8wlH24pgwQHzy7Ko2qLwn1b5PW8ecrlvP1g
	1645  -----END RSA TESTING KEY-----`)))
	1646  	if err != nil {
	1647  		t.Fatal(err)
	1648  	}
	1649  
	1650  	clientConn, serverConn := localPipe(t)
	1651  	client := Client(clientConn, testConfig)
	1652  	done := make(chan struct{})
	1653  	go func() {
	1654  		config := testConfig.Clone()
	1655  		config.Certificates = []Certificate{cert}
	1656  		config.MinVersion = VersionTLS13
	1657  		server := Server(serverConn, config)
	1658  		err := server.Handshake()
	1659  		expectError(t, err, "key size too small")
	1660  		close(done)
	1661  	}()
	1662  	err = client.Handshake()
	1663  	expectError(t, err, "handshake failure")
	1664  	<-done
	1665  }
	1666  
	1667  func TestMultipleCertificates(t *testing.T) {
	1668  	clientConfig := testConfig.Clone()
	1669  	clientConfig.CipherSuites = []uint16{TLS_RSA_WITH_AES_128_GCM_SHA256}
	1670  	clientConfig.MaxVersion = VersionTLS12
	1671  
	1672  	serverConfig := testConfig.Clone()
	1673  	serverConfig.Certificates = []Certificate{{
	1674  		Certificate: [][]byte{testECDSACertificate},
	1675  		PrivateKey:	testECDSAPrivateKey,
	1676  	}, {
	1677  		Certificate: [][]byte{testRSACertificate},
	1678  		PrivateKey:	testRSAPrivateKey,
	1679  	}}
	1680  
	1681  	_, clientState, err := testHandshake(t, clientConfig, serverConfig)
	1682  	if err != nil {
	1683  		t.Fatal(err)
	1684  	}
	1685  	if got := clientState.PeerCertificates[0].PublicKeyAlgorithm; got != x509.RSA {
	1686  		t.Errorf("expected RSA certificate, got %v", got)
	1687  	}
	1688  }
	1689  
	1690  func TestAESCipherReordering(t *testing.T) {
	1691  	currentAESSupport := hasAESGCMHardwareSupport
	1692  	defer func() { hasAESGCMHardwareSupport = currentAESSupport }()
	1693  
	1694  	tests := []struct {
	1695  		name						string
	1696  		clientCiphers	 []uint16
	1697  		serverHasAESGCM bool
	1698  		serverCiphers	 []uint16
	1699  		expectedCipher	uint16
	1700  	}{
	1701  		{
	1702  			name: "server has hardware AES, client doesn't (pick ChaCha)",
	1703  			clientCiphers: []uint16{
	1704  				TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305,
	1705  				TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
	1706  				TLS_RSA_WITH_AES_128_CBC_SHA,
	1707  			},
	1708  			serverHasAESGCM: true,
	1709  			expectedCipher:	TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305,
	1710  		},
	1711  		{
	1712  			name: "client prefers AES-GCM, server doesn't have hardware AES (pick ChaCha)",
	1713  			clientCiphers: []uint16{
	1714  				TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
	1715  				TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305,
	1716  				TLS_RSA_WITH_AES_128_CBC_SHA,
	1717  			},
	1718  			serverHasAESGCM: false,
	1719  			expectedCipher:	TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305,
	1720  		},
	1721  		{
	1722  			name: "client prefers AES-GCM, server has hardware AES (pick AES-GCM)",
	1723  			clientCiphers: []uint16{
	1724  				TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
	1725  				TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305,
	1726  				TLS_RSA_WITH_AES_128_CBC_SHA,
	1727  			},
	1728  			serverHasAESGCM: true,
	1729  			expectedCipher:	TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
	1730  		},
	1731  		{
	1732  			name: "client prefers AES-GCM and sends GREASE, server has hardware AES (pick AES-GCM)",
	1733  			clientCiphers: []uint16{
	1734  				0x0A0A, // GREASE value
	1735  				TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
	1736  				TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305,
	1737  				TLS_RSA_WITH_AES_128_CBC_SHA,
	1738  			},
	1739  			serverHasAESGCM: true,
	1740  			expectedCipher:	TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
	1741  		},
	1742  		{
	1743  			name: "client prefers AES-GCM and doesn't support ChaCha, server doesn't have hardware AES (pick AES-GCM)",
	1744  			clientCiphers: []uint16{
	1745  				TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
	1746  				TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
	1747  				TLS_RSA_WITH_AES_128_CBC_SHA,
	1748  			},
	1749  			serverHasAESGCM: false,
	1750  			expectedCipher:	TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
	1751  		},
	1752  		{
	1753  			name: "client prefers AES-GCM and AES-CBC over ChaCha, server doesn't have hardware AES (pick ChaCha)",
	1754  			clientCiphers: []uint16{
	1755  				TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
	1756  				TLS_RSA_WITH_AES_128_CBC_SHA,
	1757  				TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305,
	1758  			},
	1759  			serverHasAESGCM: false,
	1760  			expectedCipher:	TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305,
	1761  		},
	1762  		{
	1763  			name: "client prefers AES-GCM over ChaCha and sends GREASE, server doesn't have hardware AES (pick ChaCha)",
	1764  			clientCiphers: []uint16{
	1765  				0x0A0A, // GREASE value
	1766  				TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
	1767  				TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305,
	1768  				TLS_RSA_WITH_AES_128_CBC_SHA,
	1769  			},
	1770  			serverHasAESGCM: false,
	1771  			expectedCipher:	TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305,
	1772  		},
	1773  		{
	1774  			name: "client supports multiple AES-GCM, server doesn't have hardware AES and doesn't support ChaCha (AES-GCM)",
	1775  			clientCiphers: []uint16{
	1776  				TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
	1777  				TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305,
	1778  				TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
	1779  			},
	1780  			serverHasAESGCM: false,
	1781  			serverCiphers: []uint16{
	1782  				TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
	1783  				TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
	1784  			},
	1785  			expectedCipher: TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
	1786  		},
	1787  		{
	1788  			name: "client prefers AES-GCM, server has hardware but doesn't support AES (pick ChaCha)",
	1789  			clientCiphers: []uint16{
	1790  				TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
	1791  				TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305,
	1792  				TLS_RSA_WITH_AES_128_CBC_SHA,
	1793  			},
	1794  			serverHasAESGCM: true,
	1795  			serverCiphers: []uint16{
	1796  				TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305,
	1797  			},
	1798  			expectedCipher: TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305,
	1799  		},
	1800  	}
	1801  
	1802  	for _, tc := range tests {
	1803  		t.Run(tc.name, func(t *testing.T) {
	1804  			hasAESGCMHardwareSupport = tc.serverHasAESGCM
	1805  			hs := &serverHandshakeState{
	1806  				c: &Conn{
	1807  					config: &Config{
	1808  						CipherSuites: tc.serverCiphers,
	1809  					},
	1810  					vers: VersionTLS12,
	1811  				},
	1812  				clientHello: &clientHelloMsg{
	1813  					cipherSuites: tc.clientCiphers,
	1814  					vers:				 VersionTLS12,
	1815  				},
	1816  				ecdheOk:			true,
	1817  				rsaSignOk:		true,
	1818  				rsaDecryptOk: true,
	1819  			}
	1820  
	1821  			err := hs.pickCipherSuite()
	1822  			if err != nil {
	1823  				t.Errorf("pickCipherSuite failed: %s", err)
	1824  			}
	1825  
	1826  			if tc.expectedCipher != hs.suite.id {
	1827  				t.Errorf("unexpected cipher chosen: want %d, got %d", tc.expectedCipher, hs.suite.id)
	1828  			}
	1829  		})
	1830  	}
	1831  }
	1832  
	1833  func TestAESCipherReorderingTLS13(t *testing.T) {
	1834  	currentAESSupport := hasAESGCMHardwareSupport
	1835  	defer func() { hasAESGCMHardwareSupport = currentAESSupport }()
	1836  
	1837  	tests := []struct {
	1838  		name						string
	1839  		clientCiphers	 []uint16
	1840  		serverHasAESGCM bool
	1841  		expectedCipher	uint16
	1842  	}{
	1843  		{
	1844  			name: "server has hardware AES, client doesn't (pick ChaCha)",
	1845  			clientCiphers: []uint16{
	1846  				TLS_CHACHA20_POLY1305_SHA256,
	1847  				TLS_AES_128_GCM_SHA256,
	1848  			},
	1849  			serverHasAESGCM: true,
	1850  			expectedCipher:	TLS_CHACHA20_POLY1305_SHA256,
	1851  		},
	1852  		{
	1853  			name: "neither server nor client have hardware AES (pick ChaCha)",
	1854  			clientCiphers: []uint16{
	1855  				TLS_CHACHA20_POLY1305_SHA256,
	1856  				TLS_AES_128_GCM_SHA256,
	1857  			},
	1858  			serverHasAESGCM: false,
	1859  			expectedCipher:	TLS_CHACHA20_POLY1305_SHA256,
	1860  		},
	1861  		{
	1862  			name: "client prefers AES, server doesn't have hardware (pick ChaCha)",
	1863  			clientCiphers: []uint16{
	1864  				TLS_AES_128_GCM_SHA256,
	1865  				TLS_CHACHA20_POLY1305_SHA256,
	1866  			},
	1867  			serverHasAESGCM: false,
	1868  			expectedCipher:	TLS_CHACHA20_POLY1305_SHA256,
	1869  		},
	1870  		{
	1871  			name: "client prefers AES and sends GREASE, server doesn't have hardware (pick ChaCha)",
	1872  			clientCiphers: []uint16{
	1873  				0x0A0A, // GREASE value
	1874  				TLS_AES_128_GCM_SHA256,
	1875  				TLS_CHACHA20_POLY1305_SHA256,
	1876  			},
	1877  			serverHasAESGCM: false,
	1878  			expectedCipher:	TLS_CHACHA20_POLY1305_SHA256,
	1879  		},
	1880  		{
	1881  			name: "client prefers AES, server has hardware AES (pick AES)",
	1882  			clientCiphers: []uint16{
	1883  				TLS_AES_128_GCM_SHA256,
	1884  				TLS_CHACHA20_POLY1305_SHA256,
	1885  			},
	1886  			serverHasAESGCM: true,
	1887  			expectedCipher:	TLS_AES_128_GCM_SHA256,
	1888  		},
	1889  		{
	1890  			name: "client prefers AES and sends GREASE, server has hardware AES (pick AES)",
	1891  			clientCiphers: []uint16{
	1892  				0x0A0A, // GREASE value
	1893  				TLS_AES_128_GCM_SHA256,
	1894  				TLS_CHACHA20_POLY1305_SHA256,
	1895  			},
	1896  			serverHasAESGCM: true,
	1897  			expectedCipher:	TLS_AES_128_GCM_SHA256,
	1898  		},
	1899  	}
	1900  
	1901  	for _, tc := range tests {
	1902  		t.Run(tc.name, func(t *testing.T) {
	1903  			hasAESGCMHardwareSupport = tc.serverHasAESGCM
	1904  			hs := &serverHandshakeStateTLS13{
	1905  				c: &Conn{
	1906  					config: &Config{},
	1907  					vers:	 VersionTLS13,
	1908  				},
	1909  				clientHello: &clientHelloMsg{
	1910  					cipherSuites:			 tc.clientCiphers,
	1911  					supportedVersions:	[]uint16{VersionTLS13},
	1912  					compressionMethods: []uint8{compressionNone},
	1913  					keyShares:					[]keyShare{{group: X25519, data: curve25519.Basepoint}},
	1914  				},
	1915  			}
	1916  
	1917  			err := hs.processClientHello()
	1918  			if err != nil {
	1919  				t.Errorf("pickCipherSuite failed: %s", err)
	1920  			}
	1921  
	1922  			if tc.expectedCipher != hs.suite.id {
	1923  				t.Errorf("unexpected cipher chosen: want %d, got %d", tc.expectedCipher, hs.suite.id)
	1924  			}
	1925  		})
	1926  	}
	1927  }
	1928  
	1929  // TestServerHandshakeContextCancellation tests that cancelling
	1930  // the context given to the server side conn.HandshakeContext
	1931  // interrupts the in-progress handshake.
	1932  func TestServerHandshakeContextCancellation(t *testing.T) {
	1933  	c, s := localPipe(t)
	1934  	ctx, cancel := context.WithCancel(context.Background())
	1935  	unblockClient := make(chan struct{})
	1936  	defer close(unblockClient)
	1937  	go func() {
	1938  		cancel()
	1939  		<-unblockClient
	1940  		_ = c.Close()
	1941  	}()
	1942  	conn := Server(s, testConfig)
	1943  	// Initiates server side handshake, which will block until a client hello is read
	1944  	// unless the cancellation works.
	1945  	err := conn.HandshakeContext(ctx)
	1946  	if err == nil {
	1947  		t.Fatal("Server handshake did not error when the context was canceled")
	1948  	}
	1949  	if err != context.Canceled {
	1950  		t.Errorf("Unexpected server handshake error: %v", err)
	1951  	}
	1952  	if runtime.GOARCH == "wasm" {
	1953  		t.Skip("conn.Close does not error as expected when called multiple times on WASM")
	1954  	}
	1955  	err = conn.Close()
	1956  	if err == nil {
	1957  		t.Error("Server connection was not closed when the context was canceled")
	1958  	}
	1959  }
	1960  
	1961  // TestHandshakeContextHierarchy tests whether the contexts
	1962  // available to GetClientCertificate and GetCertificate are
	1963  // derived from the context provided to HandshakeContext, and
	1964  // that those contexts are canceled after HandshakeContext has
	1965  // returned.
	1966  func TestHandshakeContextHierarchy(t *testing.T) {
	1967  	c, s := localPipe(t)
	1968  	clientErr := make(chan error, 1)
	1969  	clientConfig := testConfig.Clone()
	1970  	serverConfig := testConfig.Clone()
	1971  	ctx, cancel := context.WithCancel(context.Background())
	1972  	defer cancel()
	1973  	key := struct{}{}
	1974  	ctx = context.WithValue(ctx, key, true)
	1975  	go func() {
	1976  		defer close(clientErr)
	1977  		defer c.Close()
	1978  		var innerCtx context.Context
	1979  		clientConfig.Certificates = nil
	1980  		clientConfig.GetClientCertificate = func(certificateRequest *CertificateRequestInfo) (*Certificate, error) {
	1981  			if val, ok := certificateRequest.Context().Value(key).(bool); !ok || !val {
	1982  				t.Errorf("GetClientCertificate context was not child of HandshakeContext")
	1983  			}
	1984  			innerCtx = certificateRequest.Context()
	1985  			return &Certificate{
	1986  				Certificate: [][]byte{testRSACertificate},
	1987  				PrivateKey:	testRSAPrivateKey,
	1988  			}, nil
	1989  		}
	1990  		cli := Client(c, clientConfig)
	1991  		err := cli.HandshakeContext(ctx)
	1992  		if err != nil {
	1993  			clientErr <- err
	1994  			return
	1995  		}
	1996  		select {
	1997  		case <-innerCtx.Done():
	1998  		default:
	1999  			t.Errorf("GetClientCertificate context was not canceled after HandshakeContext returned.")
	2000  		}
	2001  	}()
	2002  	var innerCtx context.Context
	2003  	serverConfig.Certificates = nil
	2004  	serverConfig.ClientAuth = RequestClientCert
	2005  	serverConfig.GetCertificate = func(clientHello *ClientHelloInfo) (*Certificate, error) {
	2006  		if val, ok := clientHello.Context().Value(key).(bool); !ok || !val {
	2007  			t.Errorf("GetClientCertificate context was not child of HandshakeContext")
	2008  		}
	2009  		innerCtx = clientHello.Context()
	2010  		return &Certificate{
	2011  			Certificate: [][]byte{testRSACertificate},
	2012  			PrivateKey:	testRSAPrivateKey,
	2013  		}, nil
	2014  	}
	2015  	conn := Server(s, serverConfig)
	2016  	err := conn.HandshakeContext(ctx)
	2017  	if err != nil {
	2018  		t.Errorf("Unexpected server handshake error: %v", err)
	2019  	}
	2020  	select {
	2021  	case <-innerCtx.Done():
	2022  	default:
	2023  		t.Errorf("GetCertificate context was not canceled after HandshakeContext returned.")
	2024  	}
	2025  	if err := <-clientErr; err != nil {
	2026  		t.Errorf("Unexpected client error: %v", err)
	2027  	}
	2028  }
	2029  

View as plain text