handshake_client.mx raw

   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/ecdsa"
  12  	"crypto/ed25519"
  13  	"crypto/hpke"
  14  	"crypto/internal/fips140/tls13"
  15  	"crypto/rsa"
  16  	"crypto/subtle"
  17  	"crypto/tls/internal/fips140tls"
  18  	"crypto/x509"
  19  	"errors"
  20  	"fmt"
  21  	"hash"
  22  	"internal/godebug"
  23  	"io"
  24  	"net"
  25  	"slices"
  26  	"strconv"
  27  	"time"
  28  )
  29  
  30  type clientHandshakeState struct {
  31  	c            *Conn
  32  	ctx          context.Context
  33  	serverHello  *serverHelloMsg
  34  	hello        *clientHelloMsg
  35  	suite        *cipherSuite
  36  	finishedHash finishedHash
  37  	masterSecret []byte
  38  	session      *SessionState // the session being resumed
  39  	ticket       []byte        // a fresh ticket received during this handshake
  40  }
  41  
  42  func (c *Conn) makeClientHello() (*clientHelloMsg, *keySharePrivateKeys, *echClientContext, error) {
  43  	config := c.config
  44  	if len(config.ServerName) == 0 && !config.InsecureSkipVerify {
  45  		return nil, nil, nil, errors.New("tls: either ServerName or InsecureSkipVerify must be specified in the tls.Config")
  46  	}
  47  
  48  	nextProtosLength := 0
  49  	for _, proto := range config.NextProtos {
  50  		if l := len(proto); l == 0 || l > 255 {
  51  			return nil, nil, nil, errors.New("tls: invalid NextProtos value")
  52  		} else {
  53  			nextProtosLength += 1 + l
  54  		}
  55  	}
  56  	if nextProtosLength > 0xffff {
  57  		return nil, nil, nil, errors.New("tls: NextProtos values too large")
  58  	}
  59  
  60  	supportedVersions := config.supportedVersions(roleClient)
  61  	if len(supportedVersions) == 0 {
  62  		return nil, nil, nil, errors.New("tls: no supported versions satisfy MinVersion and MaxVersion")
  63  	}
  64  	// Since supportedVersions is sorted in descending order, the first element
  65  	// is the maximum version and the last element is the minimum version.
  66  	maxVersion := supportedVersions[0]
  67  	minVersion := supportedVersions[len(supportedVersions)-1]
  68  
  69  	hello := &clientHelloMsg{
  70  		vers:                         maxVersion,
  71  		compressionMethods:           []uint8{compressionNone},
  72  		random:                       []byte{:32},
  73  		extendedMasterSecret:         true,
  74  		ocspStapling:                 true,
  75  		scts:                         true,
  76  		serverName:                   hostnameInSNI(config.ServerName),
  77  		supportedCurves:              config.curvePreferences(maxVersion),
  78  		supportedPoints:              []uint8{pointFormatUncompressed},
  79  		secureRenegotiationSupported: true,
  80  		alpnProtocols:                config.NextProtos,
  81  		supportedVersions:            supportedVersions,
  82  	}
  83  
  84  	// The version at the beginning of the ClientHello was capped at TLS 1.2
  85  	// for compatibility reasons. The supported_versions extension is used
  86  	// to negotiate versions now. See RFC 8446, Section 4.2.1.
  87  	if hello.vers > VersionTLS12 {
  88  		hello.vers = VersionTLS12
  89  	}
  90  
  91  	if c.handshakes > 0 {
  92  		hello.secureRenegotiation = c.clientFinished[:]
  93  	}
  94  
  95  	hello.cipherSuites = config.cipherSuites(hasAESGCMHardwareSupport)
  96  	// Don't advertise TLS 1.2-only cipher suites unless we're attempting TLS 1.2.
  97  	if maxVersion < VersionTLS12 {
  98  		hello.cipherSuites = slices.DeleteFunc(hello.cipherSuites, func(id uint16) bool {
  99  			return cipherSuiteByID(id).flags&suiteTLS12 != 0
 100  		})
 101  	}
 102  
 103  	_, err := io.ReadFull(config.rand(), hello.random)
 104  	if err != nil {
 105  		return nil, nil, nil, errors.New("tls: short read from Rand: " + err.Error())
 106  	}
 107  
 108  	// A random session ID is used to detect when the server accepted a ticket
 109  	// and is resuming a session (see RFC 5077). In TLS 1.3, it's always set as
 110  	// a compatibility measure (see RFC 8446, Section 4.1.2).
 111  	//
 112  	// The session ID is not set for QUIC connections (see RFC 9001, Section 8.4).
 113  	if c.quic == nil {
 114  		hello.sessionId = []byte{:32}
 115  		if _, err := io.ReadFull(config.rand(), hello.sessionId); err != nil {
 116  			return nil, nil, nil, errors.New("tls: short read from Rand: " + err.Error())
 117  		}
 118  	}
 119  
 120  	if maxVersion >= VersionTLS12 {
 121  		hello.supportedSignatureAlgorithms = supportedSignatureAlgorithms(minVersion)
 122  		hello.supportedSignatureAlgorithmsCert = supportedSignatureAlgorithmsCert()
 123  	}
 124  
 125  	var keyShareKeys *keySharePrivateKeys
 126  	if maxVersion >= VersionTLS13 {
 127  		// Reset the list of ciphers when the client only supports TLS 1.3.
 128  		if minVersion >= VersionTLS13 {
 129  			hello.cipherSuites = nil
 130  		}
 131  
 132  		if fips140tls.Required() {
 133  			hello.cipherSuites = append(hello.cipherSuites, allowedCipherSuitesTLS13FIPS...)
 134  		} else if hasAESGCMHardwareSupport {
 135  			hello.cipherSuites = append(hello.cipherSuites, defaultCipherSuitesTLS13...)
 136  		} else {
 137  			hello.cipherSuites = append(hello.cipherSuites, defaultCipherSuitesTLS13NoAES...)
 138  		}
 139  
 140  		if len(hello.supportedCurves) == 0 {
 141  			return nil, nil, nil, errors.New("tls: no supported elliptic curves for ECDHE")
 142  		}
 143  		// Since the order is fixed, the first one is always the one to send a
 144  		// key share for. All the PQ hybrids sort first, and produce a fallback
 145  		// ECDH share.
 146  		curveID := hello.supportedCurves[0]
 147  		ke, err := keyExchangeForCurveID(curveID)
 148  		if err != nil {
 149  			return nil, nil, nil, errors.New("tls: CurvePreferences includes unsupported curve")
 150  		}
 151  		keyShareKeys, hello.keyShares, err = ke.keyShares(config.rand())
 152  		if err != nil {
 153  			return nil, nil, nil, err
 154  		}
 155  		// Only send the fallback ECDH share if the corresponding CurveID is enabled.
 156  		if len(hello.keyShares) == 2 && !slices.Contains(hello.supportedCurves, hello.keyShares[1].group) {
 157  			hello.keyShares = hello.keyShares[:1]
 158  		}
 159  	}
 160  
 161  	if c.quic != nil {
 162  		p, err := c.quicGetTransportParameters()
 163  		if err != nil {
 164  			return nil, nil, nil, err
 165  		}
 166  		if p == nil {
 167  			p = []byte{}
 168  		}
 169  		hello.quicTransportParameters = p
 170  	}
 171  
 172  	var ech *echClientContext
 173  	if c.config.EncryptedClientHelloConfigList != nil {
 174  		if c.config.MinVersion != 0 && c.config.MinVersion < VersionTLS13 {
 175  			return nil, nil, nil, errors.New("tls: MinVersion must be >= VersionTLS13 if EncryptedClientHelloConfigList is populated")
 176  		}
 177  		if c.config.MaxVersion != 0 && c.config.MaxVersion <= VersionTLS12 {
 178  			return nil, nil, nil, errors.New("tls: MaxVersion must be >= VersionTLS13 if EncryptedClientHelloConfigList is populated")
 179  		}
 180  		echConfigs, err := parseECHConfigList(c.config.EncryptedClientHelloConfigList)
 181  		if err != nil {
 182  			return nil, nil, nil, err
 183  		}
 184  		echConfig, echPK, kdf, aead := pickECHConfig(echConfigs)
 185  		if echConfig == nil {
 186  			return nil, nil, nil, errors.New("tls: EncryptedClientHelloConfigList contains no valid configs")
 187  		}
 188  		ech = &echClientContext{config: echConfig, kdfID: kdf.ID(), aeadID: aead.ID()}
 189  		hello.encryptedClientHello = []byte{1} // indicate inner hello
 190  		// We need to explicitly set these 1.2 fields to nil, as we do not
 191  		// marshal them when encoding the inner hello, otherwise transcripts
 192  		// will later mismatch.
 193  		hello.supportedPoints = nil
 194  		hello.ticketSupported = false
 195  		hello.secureRenegotiationSupported = false
 196  		hello.extendedMasterSecret = false
 197  
 198  		info := append([]byte("tls ech\x00"), ech.config.raw...)
 199  		ech.encapsulatedKey, ech.hpkeContext, err = hpke.NewSender(echPK, kdf, aead, info)
 200  		if err != nil {
 201  			return nil, nil, nil, err
 202  		}
 203  	}
 204  
 205  	return hello, keyShareKeys, ech, nil
 206  }
 207  
 208  type echClientContext struct {
 209  	config          *echConfig
 210  	hpkeContext     *hpke.Sender
 211  	encapsulatedKey []byte
 212  	innerHello      *clientHelloMsg
 213  	innerTranscript hash.Hash
 214  	kdfID           uint16
 215  	aeadID          uint16
 216  	echRejected     bool
 217  	retryConfigs    []byte
 218  }
 219  
 220  func (c *Conn) clientHandshake(ctx context.Context) (err error) {
 221  	if c.config == nil {
 222  		c.config = defaultConfig()
 223  	}
 224  
 225  	// This may be a renegotiation handshake, in which case some fields
 226  	// need to be reset.
 227  	c.didResume = false
 228  	c.curveID = 0
 229  
 230  	hello, keyShareKeys, ech, err := c.makeClientHello()
 231  	if err != nil {
 232  		return err
 233  	}
 234  
 235  	session, earlySecret, binderKey, err := c.loadSession(hello)
 236  	if err != nil {
 237  		return err
 238  	}
 239  	if session != nil {
 240  		defer func() {
 241  			// If we got a handshake failure when resuming a session, throw away
 242  			// the session ticket. See RFC 5077, Section 3.2.
 243  			//
 244  			// RFC 8446 makes no mention of dropping tickets on failure, but it
 245  			// does require servers to abort on invalid binders, so we need to
 246  			// delete tickets to recover from a corrupted PSK.
 247  			if err != nil {
 248  				if cacheKey := c.clientSessionCacheKey(); cacheKey != "" {
 249  					c.config.ClientSessionCache.Put(cacheKey, nil)
 250  				}
 251  			}
 252  		}()
 253  	}
 254  
 255  	if ech != nil {
 256  		// Split hello into inner and outer
 257  		ech.innerHello = hello.clone()
 258  
 259  		// Overwrite the server name in the outer hello with the public facing
 260  		// name.
 261  		hello.serverName = []byte(ech.config.PublicName)
 262  		// Generate a new random for the outer hello.
 263  		hello.random = []byte{:32}
 264  		_, err = io.ReadFull(c.config.rand(), hello.random)
 265  		if err != nil {
 266  			return errors.New("tls: short read from Rand: " + err.Error())
 267  		}
 268  
 269  		// NOTE: we don't do PSK GREASE, in line with boringssl, it's meant to
 270  		// work around _possibly_ broken middleboxes, but there is little-to-no
 271  		// evidence that this is actually a problem.
 272  
 273  		if err := computeAndUpdateOuterECHExtension(hello, ech.innerHello, ech, true); err != nil {
 274  			return err
 275  		}
 276  	}
 277  
 278  	c.serverName = hello.serverName
 279  
 280  	if _, err := c.writeHandshakeRecord(hello, nil); err != nil {
 281  		return err
 282  	}
 283  
 284  	if hello.earlyData {
 285  		suite := cipherSuiteTLS13ByID(session.cipherSuite)
 286  		transcript := suite.hash.New()
 287  		transcriptHello := hello
 288  		if ech != nil {
 289  			transcriptHello = ech.innerHello
 290  		}
 291  		if err := transcriptMsg(transcriptHello, transcript); err != nil {
 292  			return err
 293  		}
 294  		earlyTrafficSecret := earlySecret.ClientEarlyTrafficSecret(transcript)
 295  		c.quicSetWriteSecret(QUICEncryptionLevelEarly, suite.id, earlyTrafficSecret)
 296  	}
 297  
 298  	// serverHelloMsg is not included in the transcript
 299  	msg, err := c.readHandshake(nil)
 300  	if err != nil {
 301  		return err
 302  	}
 303  
 304  	serverHello, ok := msg.(*serverHelloMsg)
 305  	if !ok {
 306  		c.sendAlert(alertUnexpectedMessage)
 307  		return unexpectedMessageError(serverHello, msg)
 308  	}
 309  
 310  	if err := c.pickTLSVersion(serverHello); err != nil {
 311  		return err
 312  	}
 313  
 314  	// If we are negotiating a protocol version that's lower than what we
 315  	// support, check for the server downgrade canaries.
 316  	// See RFC 8446, Section 4.1.3.
 317  	maxVers := c.config.maxSupportedVersion(roleClient)
 318  	tls12Downgrade := []byte(serverHello.random[24:]) == downgradeCanaryTLS12
 319  	tls11Downgrade := []byte(serverHello.random[24:]) == downgradeCanaryTLS11
 320  	if maxVers == VersionTLS13 && c.vers <= VersionTLS12 && (tls12Downgrade || tls11Downgrade) ||
 321  		maxVers == VersionTLS12 && c.vers <= VersionTLS11 && tls11Downgrade {
 322  		c.sendAlert(alertIllegalParameter)
 323  		return errors.New("tls: downgrade attempt detected, possibly due to a MitM attack or a broken middlebox")
 324  	}
 325  
 326  	if c.vers == VersionTLS13 {
 327  		hs := &clientHandshakeStateTLS13{
 328  			c:            c,
 329  			ctx:          ctx,
 330  			serverHello:  serverHello,
 331  			hello:        hello,
 332  			keyShareKeys: keyShareKeys,
 333  			session:      session,
 334  			earlySecret:  earlySecret,
 335  			binderKey:    binderKey,
 336  			echContext:   ech,
 337  		}
 338  		return hs.handshake()
 339  	}
 340  
 341  	hs := &clientHandshakeState{
 342  		c:           c,
 343  		ctx:         ctx,
 344  		serverHello: serverHello,
 345  		hello:       hello,
 346  		session:     session,
 347  	}
 348  	return hs.handshake()
 349  }
 350  
 351  func (c *Conn) loadSession(hello *clientHelloMsg) (
 352  	session *SessionState, earlySecret *tls13.EarlySecret, binderKey []byte, err error) {
 353  	if c.config.SessionTicketsDisabled || c.config.ClientSessionCache == nil {
 354  		return nil, nil, nil, nil
 355  	}
 356  
 357  	echInner := bytes.Equal(hello.encryptedClientHello, []byte{1})
 358  
 359  	// ticketSupported is a TLS 1.2 extension (as TLS 1.3 replaced tickets with PSK
 360  	// identities) and ECH requires and forces TLS 1.3.
 361  	hello.ticketSupported = true && !echInner
 362  
 363  	if hello.supportedVersions[0] == VersionTLS13 {
 364  		// Require DHE on resumption as it guarantees forward secrecy against
 365  		// compromise of the session ticket key. See RFC 8446, Section 4.2.9.
 366  		hello.pskModes = []uint8{pskModeDHE}
 367  	}
 368  
 369  	// Session resumption is not allowed if renegotiating because
 370  	// renegotiation is primarily used to allow a client to send a client
 371  	// certificate, which would be skipped if session resumption occurred.
 372  	if c.handshakes != 0 {
 373  		return nil, nil, nil, nil
 374  	}
 375  
 376  	// Try to resume a previously negotiated TLS session, if available.
 377  	cacheKey := c.clientSessionCacheKey()
 378  	if cacheKey == "" {
 379  		return nil, nil, nil, nil
 380  	}
 381  	cs, ok := c.config.ClientSessionCache.Get(cacheKey)
 382  	if !ok || cs == nil {
 383  		return nil, nil, nil, nil
 384  	}
 385  	session = cs.session
 386  
 387  	// Check that version used for the previous session is still valid.
 388  	versOk := false
 389  	for _, v := range hello.supportedVersions {
 390  		if v == session.version {
 391  			versOk = true
 392  			break
 393  		}
 394  	}
 395  	if !versOk {
 396  		return nil, nil, nil, nil
 397  	}
 398  
 399  	if c.config.time().After(session.peerCertificates[0].NotAfter) {
 400  		// Expired certificate, delete the entry.
 401  		c.config.ClientSessionCache.Put(cacheKey, nil)
 402  		return nil, nil, nil, nil
 403  	}
 404  	if !c.config.InsecureSkipVerify {
 405  		if len(session.verifiedChains) == 0 {
 406  			// The original connection had InsecureSkipVerify, while this doesn't.
 407  			return nil, nil, nil, nil
 408  		}
 409  		if err := session.peerCertificates[0].VerifyHostname(c.config.ServerName); err != nil {
 410  			// This should be ensured by the cache key, but protect the
 411  			// application from a faulty ClientSessionCache implementation.
 412  			return nil, nil, nil, nil
 413  		}
 414  		opts := x509.VerifyOptions{
 415  			CurrentTime: c.config.time(),
 416  			Roots:       c.config.RootCAs,
 417  			KeyUsages:   []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
 418  		}
 419  		if !anyValidVerifiedChain(session.verifiedChains, opts) {
 420  			// No valid chains, delete the entry.
 421  			c.config.ClientSessionCache.Put(cacheKey, nil)
 422  			return nil, nil, nil, nil
 423  		}
 424  	}
 425  
 426  	if session.version != VersionTLS13 {
 427  		// In TLS 1.2 the cipher suite must match the resumed session. Ensure we
 428  		// are still offering it.
 429  		if mutualCipherSuite(hello.cipherSuites, session.cipherSuite) == nil {
 430  			return nil, nil, nil, nil
 431  		}
 432  
 433  		// FIPS 140-3 requires the use of Extended Master Secret.
 434  		if !session.extMasterSecret && fips140tls.Required() {
 435  			return nil, nil, nil, nil
 436  		}
 437  
 438  		hello.sessionTicket = session.ticket
 439  		return
 440  	}
 441  
 442  	// Check that the session ticket is not expired.
 443  	if c.config.time().After(time.Unix(int64(session.useBy), 0)) {
 444  		c.config.ClientSessionCache.Put(cacheKey, nil)
 445  		return nil, nil, nil, nil
 446  	}
 447  
 448  	// In TLS 1.3 the KDF hash must match the resumed session. Ensure we
 449  	// offer at least one cipher suite with that hash.
 450  	cipherSuite := cipherSuiteTLS13ByID(session.cipherSuite)
 451  	if cipherSuite == nil {
 452  		return nil, nil, nil, nil
 453  	}
 454  	cipherSuiteOk := false
 455  	for _, offeredID := range hello.cipherSuites {
 456  		offeredSuite := cipherSuiteTLS13ByID(offeredID)
 457  		if offeredSuite != nil && offeredSuite.hash == cipherSuite.hash {
 458  			cipherSuiteOk = true
 459  			break
 460  		}
 461  	}
 462  	if !cipherSuiteOk {
 463  		return nil, nil, nil, nil
 464  	}
 465  
 466  	if c.quic != nil {
 467  		if c.quic.enableSessionEvents {
 468  			c.quicResumeSession(session)
 469  		}
 470  
 471  		// For 0-RTT, the cipher suite has to match exactly, and we need to be
 472  		// offering the same ALPN.
 473  		if session.EarlyData && mutualCipherSuiteTLS13(hello.cipherSuites, session.cipherSuite) != nil {
 474  			for _, alpn := range hello.alpnProtocols {
 475  				if alpn == session.alpnProtocol {
 476  					hello.earlyData = true
 477  					break
 478  				}
 479  			}
 480  		}
 481  	}
 482  
 483  	// Set the pre_shared_key extension. See RFC 8446, Section 4.2.11.1.
 484  	ticketAge := c.config.time().Sub(time.Unix(int64(session.createdAt), 0))
 485  	identity := pskIdentity{
 486  		label:               session.ticket,
 487  		obfuscatedTicketAge: uint32(ticketAge/time.Millisecond) + session.ageAdd,
 488  	}
 489  	hello.pskIdentities = []pskIdentity{identity}
 490  	hello.pskBinders = [][]byte{[]byte{:cipherSuite.hash.Size()}}
 491  
 492  	// Compute the PSK binders. See RFC 8446, Section 4.2.11.2.
 493  	earlySecret = tls13.NewEarlySecret(cipherSuite.hash.New, session.secret)
 494  	binderKey = earlySecret.ResumptionBinderKey()
 495  	transcript := cipherSuite.hash.New()
 496  	if err := computeAndUpdatePSK(hello, binderKey, transcript, cipherSuite.finishedHash); err != nil {
 497  		return nil, nil, nil, err
 498  	}
 499  
 500  	return
 501  }
 502  
 503  func (c *Conn) pickTLSVersion(serverHello *serverHelloMsg) error {
 504  	peerVersion := serverHello.vers
 505  	if serverHello.supportedVersion != 0 {
 506  		peerVersion = serverHello.supportedVersion
 507  	}
 508  
 509  	vers, ok := c.config.mutualVersion(roleClient, []uint16{peerVersion})
 510  	if !ok {
 511  		c.sendAlert(alertProtocolVersion)
 512  		return fmt.Errorf("tls: server selected unsupported protocol version %x", peerVersion)
 513  	}
 514  
 515  	c.vers = vers
 516  	c.haveVers = true
 517  	c.in.version = vers
 518  	c.out.version = vers
 519  
 520  	return nil
 521  }
 522  
 523  // Does the handshake, either a full one or resumes old session. Requires hs.c,
 524  // hs.hello, hs.serverHello, and, optionally, hs.session to be set.
 525  func (hs *clientHandshakeState) handshake() error {
 526  	c := hs.c
 527  
 528  	// If we did not load a session (hs.session == nil), but we did set a
 529  	// session ID in the transmitted client hello (hs.hello.sessionId != nil),
 530  	// it means we tried to negotiate TLS 1.3 and sent a random session ID as a
 531  	// compatibility measure (see RFC 8446, Section 4.1.2).
 532  	//
 533  	// Since we're now handshaking for TLS 1.2, if the server echoed the
 534  	// transmitted ID back to us, we know mischief is afoot: the session ID
 535  	// was random and can't possibly be recognized by the server.
 536  	if hs.session == nil && hs.hello.sessionId != nil && bytes.Equal(hs.hello.sessionId, hs.serverHello.sessionId) {
 537  		c.sendAlert(alertIllegalParameter)
 538  		return errors.New("tls: server echoed TLS 1.3 compatibility session ID in TLS 1.2")
 539  	}
 540  
 541  	isResume, err := hs.processServerHello()
 542  	if err != nil {
 543  		return err
 544  	}
 545  
 546  	hs.finishedHash = newFinishedHash(c.vers, hs.suite)
 547  
 548  	// No signatures of the handshake are needed in a resumption.
 549  	// Otherwise, in a full handshake, if we don't have any certificates
 550  	// configured then we will never send a CertificateVerify message and
 551  	// thus no signatures are needed in that case either.
 552  	if isResume || (len(c.config.Certificates) == 0 && c.config.GetClientCertificate == nil) {
 553  		hs.finishedHash.discardHandshakeBuffer()
 554  	}
 555  
 556  	if err := transcriptMsg(hs.hello, &hs.finishedHash); err != nil {
 557  		return err
 558  	}
 559  	if err := transcriptMsg(hs.serverHello, &hs.finishedHash); err != nil {
 560  		return err
 561  	}
 562  
 563  	c.buffering = true
 564  	c.didResume = isResume
 565  	if isResume {
 566  		if err := hs.establishKeys(); err != nil {
 567  			return err
 568  		}
 569  		if err := hs.readSessionTicket(); err != nil {
 570  			return err
 571  		}
 572  		if err := hs.readFinished(c.serverFinished[:]); err != nil {
 573  			return err
 574  		}
 575  		c.clientFinishedIsFirst = false
 576  		// Make sure the connection is still being verified whether or not this
 577  		// is a resumption. Resumptions currently don't reverify certificates so
 578  		// they don't call verifyServerCertificate. See Issue 31641.
 579  		if c.config.VerifyConnection != nil {
 580  			if err := c.config.VerifyConnection(c.connectionStateLocked()); err != nil {
 581  				c.sendAlert(alertBadCertificate)
 582  				return err
 583  			}
 584  		}
 585  		if err := hs.sendFinished(c.clientFinished[:]); err != nil {
 586  			return err
 587  		}
 588  		if _, err := c.flush(); err != nil {
 589  			return err
 590  		}
 591  	} else {
 592  		if err := hs.doFullHandshake(); err != nil {
 593  			return err
 594  		}
 595  		if err := hs.establishKeys(); err != nil {
 596  			return err
 597  		}
 598  		if err := hs.sendFinished(c.clientFinished[:]); err != nil {
 599  			return err
 600  		}
 601  		if _, err := c.flush(); err != nil {
 602  			return err
 603  		}
 604  		c.clientFinishedIsFirst = true
 605  		if err := hs.readSessionTicket(); err != nil {
 606  			return err
 607  		}
 608  		if err := hs.readFinished(c.serverFinished[:]); err != nil {
 609  			return err
 610  		}
 611  	}
 612  	if err := hs.saveSessionTicket(); err != nil {
 613  		return err
 614  	}
 615  
 616  	c.ekm = ekmFromMasterSecret(c.vers, hs.suite, hs.masterSecret, hs.hello.random, hs.serverHello.random)
 617  	c.isHandshakeComplete.Store(true)
 618  
 619  	return nil
 620  }
 621  
 622  func (hs *clientHandshakeState) pickCipherSuite() error {
 623  	if hs.suite = mutualCipherSuite(hs.hello.cipherSuites, hs.serverHello.cipherSuite); hs.suite == nil {
 624  		hs.c.sendAlert(alertHandshakeFailure)
 625  		return errors.New("tls: server chose an unconfigured cipher suite")
 626  	}
 627  
 628  	if hs.c.config.CipherSuites == nil && !fips140tls.Required() && rsaKexCiphers[hs.suite.id] {
 629  		tlsrsakex.Value() // ensure godebug is initialized
 630  		tlsrsakex.IncNonDefault()
 631  	}
 632  	if hs.c.config.CipherSuites == nil && !fips140tls.Required() && tdesCiphers[hs.suite.id] {
 633  		tls3des.Value() // ensure godebug is initialized
 634  		tls3des.IncNonDefault()
 635  	}
 636  
 637  	hs.c.cipherSuite = hs.suite.id
 638  	return nil
 639  }
 640  
 641  func (hs *clientHandshakeState) doFullHandshake() error {
 642  	c := hs.c
 643  
 644  	msg, err := c.readHandshake(&hs.finishedHash)
 645  	if err != nil {
 646  		return err
 647  	}
 648  	certMsg, ok := msg.(*certificateMsg)
 649  	if !ok || len(certMsg.certificates) == 0 {
 650  		c.sendAlert(alertUnexpectedMessage)
 651  		return unexpectedMessageError(certMsg, msg)
 652  	}
 653  
 654  	msg, err = c.readHandshake(&hs.finishedHash)
 655  	if err != nil {
 656  		return err
 657  	}
 658  
 659  	cs, ok := msg.(*certificateStatusMsg)
 660  	if ok {
 661  		// RFC4366 on Certificate Status Request:
 662  		// The server MAY return a "certificate_status" message.
 663  
 664  		if !hs.serverHello.ocspStapling {
 665  			// If a server returns a "CertificateStatus" message, then the
 666  			// server MUST have included an extension of type "status_request"
 667  			// with empty "extension_data" in the extended server hello.
 668  
 669  			c.sendAlert(alertUnexpectedMessage)
 670  			return errors.New("tls: received unexpected CertificateStatus message")
 671  		}
 672  
 673  		c.ocspResponse = cs.response
 674  
 675  		msg, err = c.readHandshake(&hs.finishedHash)
 676  		if err != nil {
 677  			return err
 678  		}
 679  	}
 680  
 681  	if c.handshakes == 0 {
 682  		// If this is the first handshake on a connection, process and
 683  		// (optionally) verify the server's certificates.
 684  		if err := c.verifyServerCertificate(certMsg.certificates); err != nil {
 685  			return err
 686  		}
 687  	} else {
 688  		// This is a renegotiation handshake. We require that the
 689  		// server's identity (i.e. leaf certificate) is unchanged and
 690  		// thus any previous trust decision is still valid.
 691  		//
 692  		// See https://mitls.org/pages/attacks/3SHAKE for the
 693  		// motivation behind this requirement.
 694  		if !bytes.Equal(c.peerCertificates[0].Raw, certMsg.certificates[0]) {
 695  			c.sendAlert(alertBadCertificate)
 696  			return errors.New("tls: server's identity changed during renegotiation")
 697  		}
 698  	}
 699  
 700  	keyAgreement := hs.suite.ka(c.vers)
 701  
 702  	skx, ok := msg.(*serverKeyExchangeMsg)
 703  	if ok {
 704  		err = keyAgreement.processServerKeyExchange(c.config, hs.hello, hs.serverHello, c.peerCertificates[0], skx)
 705  		if err != nil {
 706  			c.sendAlert(alertIllegalParameter)
 707  			return err
 708  		}
 709  		if keyAgreement, ok := keyAgreement.(*ecdheKeyAgreement); ok {
 710  			c.curveID = keyAgreement.curveID
 711  			c.peerSigAlg = keyAgreement.signatureAlgorithm
 712  		}
 713  
 714  		msg, err = c.readHandshake(&hs.finishedHash)
 715  		if err != nil {
 716  			return err
 717  		}
 718  	}
 719  
 720  	var chainToSend *Certificate
 721  	var certRequested bool
 722  	certReq, ok := msg.(*certificateRequestMsg)
 723  	if ok {
 724  		certRequested = true
 725  
 726  		cri := certificateRequestInfoFromMsg(hs.ctx, c.vers, certReq)
 727  		if chainToSend, err = c.getClientCertificate(cri); err != nil {
 728  			c.sendAlert(alertInternalError)
 729  			return err
 730  		}
 731  
 732  		msg, err = c.readHandshake(&hs.finishedHash)
 733  		if err != nil {
 734  			return err
 735  		}
 736  	}
 737  
 738  	shd, ok := msg.(*serverHelloDoneMsg)
 739  	if !ok {
 740  		c.sendAlert(alertUnexpectedMessage)
 741  		return unexpectedMessageError(shd, msg)
 742  	}
 743  
 744  	// If the server requested a certificate then we have to send a
 745  	// Certificate message, even if it's empty because we don't have a
 746  	// certificate to send.
 747  	if certRequested {
 748  		certMsg = &certificateMsg{}
 749  		certMsg.certificates = chainToSend.Certificate
 750  		if _, err := hs.c.writeHandshakeRecord(certMsg, &hs.finishedHash); err != nil {
 751  			return err
 752  		}
 753  	}
 754  
 755  	preMasterSecret, ckx, err := keyAgreement.generateClientKeyExchange(c.config, hs.hello, c.peerCertificates[0])
 756  	if err != nil {
 757  		c.sendAlert(alertInternalError)
 758  		return err
 759  	}
 760  	if ckx != nil {
 761  		if _, err := hs.c.writeHandshakeRecord(ckx, &hs.finishedHash); err != nil {
 762  			return err
 763  		}
 764  	}
 765  
 766  	if hs.serverHello.extendedMasterSecret {
 767  		c.extMasterSecret = true
 768  		hs.masterSecret = extMasterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret,
 769  			hs.finishedHash.Sum())
 770  	} else {
 771  		if fips140tls.Required() {
 772  			c.sendAlert(alertHandshakeFailure)
 773  			return errors.New("tls: FIPS 140-3 requires the use of Extended Master Secret")
 774  		}
 775  		hs.masterSecret = masterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret,
 776  			hs.hello.random, hs.serverHello.random)
 777  	}
 778  	if err := c.config.writeKeyLog(keyLogLabelTLS12, hs.hello.random, hs.masterSecret); err != nil {
 779  		c.sendAlert(alertInternalError)
 780  		return errors.New("tls: failed to write to key log: " + err.Error())
 781  	}
 782  
 783  	if chainToSend != nil && len(chainToSend.Certificate) > 0 {
 784  		certVerify := &certificateVerifyMsg{}
 785  
 786  		key, ok := chainToSend.PrivateKey.(crypto.Signer)
 787  		if !ok {
 788  			c.sendAlert(alertInternalError)
 789  			return fmt.Errorf("tls: client certificate private key of type %T does not implement crypto.Signer", chainToSend.PrivateKey)
 790  		}
 791  
 792  		if c.vers >= VersionTLS12 {
 793  			signatureAlgorithm, err := selectSignatureScheme(c.vers, chainToSend, certReq.supportedSignatureAlgorithms)
 794  			if err != nil {
 795  				c.sendAlert(alertHandshakeFailure)
 796  				return err
 797  			}
 798  			sigType, sigHash, err := typeAndHashFromSignatureScheme(signatureAlgorithm)
 799  			if err != nil {
 800  				return c.sendAlert(alertInternalError)
 801  			}
 802  			certVerify.hasSignatureAlgorithm = true
 803  			certVerify.signatureAlgorithm = signatureAlgorithm
 804  			if sigHash == crypto.SHA1 {
 805  				tlssha1.Value() // ensure godebug is initialized
 806  				tlssha1.IncNonDefault()
 807  			}
 808  			if hs.finishedHash.buffer == nil {
 809  				c.sendAlert(alertInternalError)
 810  				return errors.New("tls: internal error: did not keep handshake transcript for TLS 1.2")
 811  			}
 812  			signOpts := crypto.SignerOpts(sigHash)
 813  			if sigType == signatureRSAPSS {
 814  				signOpts = &rsa.PSSOptions{SaltLength: rsa.PSSSaltLengthEqualsHash, Hash: sigHash}
 815  			}
 816  			certVerify.signature, err = crypto.SignMessage(key, c.config.rand(), hs.finishedHash.buffer, signOpts)
 817  			if err != nil {
 818  				c.sendAlert(alertInternalError)
 819  				return err
 820  			}
 821  		} else {
 822  			sigType, sigHash, err := legacyTypeAndHashFromPublicKey(key.Public())
 823  			if err != nil {
 824  				c.sendAlert(alertIllegalParameter)
 825  				return err
 826  			}
 827  			signed := hs.finishedHash.hashForClientCertificate(sigType)
 828  			certVerify.signature, err = key.Sign(c.config.rand(), signed, sigHash)
 829  			if err != nil {
 830  				c.sendAlert(alertInternalError)
 831  				return err
 832  			}
 833  		}
 834  
 835  		if _, err := hs.c.writeHandshakeRecord(certVerify, &hs.finishedHash); err != nil {
 836  			return err
 837  		}
 838  	}
 839  
 840  	hs.finishedHash.discardHandshakeBuffer()
 841  
 842  	return nil
 843  }
 844  
 845  func (hs *clientHandshakeState) establishKeys() error {
 846  	c := hs.c
 847  
 848  	clientMAC, serverMAC, clientKey, serverKey, clientIV, serverIV :=
 849  		keysFromMasterSecret(c.vers, hs.suite, hs.masterSecret, hs.hello.random, hs.serverHello.random, hs.suite.macLen, hs.suite.keyLen, hs.suite.ivLen)
 850  	var clientCipher, serverCipher any
 851  	var clientHash, serverHash hash.Hash
 852  	if hs.suite.cipher != nil {
 853  		clientCipher = hs.suite.cipher(clientKey, clientIV, false /* not for reading */)
 854  		clientHash = hs.suite.mac(clientMAC)
 855  		serverCipher = hs.suite.cipher(serverKey, serverIV, true /* for reading */)
 856  		serverHash = hs.suite.mac(serverMAC)
 857  	} else {
 858  		clientCipher = hs.suite.aead(clientKey, clientIV)
 859  		serverCipher = hs.suite.aead(serverKey, serverIV)
 860  	}
 861  
 862  	c.in.prepareCipherSpec(c.vers, serverCipher, serverHash)
 863  	c.out.prepareCipherSpec(c.vers, clientCipher, clientHash)
 864  	return nil
 865  }
 866  
 867  func (hs *clientHandshakeState) serverResumedSession() bool {
 868  	// If the server responded with the same sessionId then it means the
 869  	// sessionTicket is being used to resume a TLS session.
 870  	return hs.session != nil && hs.hello.sessionId != nil &&
 871  		bytes.Equal(hs.serverHello.sessionId, hs.hello.sessionId)
 872  }
 873  
 874  func (hs *clientHandshakeState) processServerHello() (bool, error) {
 875  	c := hs.c
 876  
 877  	if err := hs.pickCipherSuite(); err != nil {
 878  		return false, err
 879  	}
 880  
 881  	if hs.serverHello.compressionMethod != compressionNone {
 882  		c.sendAlert(alertIllegalParameter)
 883  		return false, errors.New("tls: server selected unsupported compression format")
 884  	}
 885  
 886  	supportsPointFormat := false
 887  	offeredNonCompressedFormat := false
 888  	for _, format := range hs.serverHello.supportedPoints {
 889  		if format == pointFormatUncompressed {
 890  			supportsPointFormat = true
 891  		} else {
 892  			offeredNonCompressedFormat = true
 893  		}
 894  	}
 895  	if !supportsPointFormat && offeredNonCompressedFormat {
 896  		return false, errors.New("tls: server offered only incompatible point formats")
 897  	}
 898  
 899  	if c.handshakes == 0 && hs.serverHello.secureRenegotiationSupported {
 900  		c.secureRenegotiation = true
 901  		if len(hs.serverHello.secureRenegotiation) != 0 {
 902  			c.sendAlert(alertHandshakeFailure)
 903  			return false, errors.New("tls: initial handshake had non-empty renegotiation extension")
 904  		}
 905  	}
 906  
 907  	if c.handshakes > 0 && c.secureRenegotiation {
 908  		var expectedSecureRenegotiation [24]byte
 909  		copy(expectedSecureRenegotiation[:], c.clientFinished[:])
 910  		copy(expectedSecureRenegotiation[12:], c.serverFinished[:])
 911  		if !bytes.Equal(hs.serverHello.secureRenegotiation, expectedSecureRenegotiation[:]) {
 912  			c.sendAlert(alertHandshakeFailure)
 913  			return false, errors.New("tls: incorrect renegotiation extension contents")
 914  		}
 915  	}
 916  
 917  	if err := checkALPN(hs.hello.alpnProtocols, hs.serverHello.alpnProtocol, false); err != nil {
 918  		c.sendAlert(alertUnsupportedExtension)
 919  		return false, err
 920  	}
 921  	c.clientProtocol = hs.serverHello.alpnProtocol
 922  
 923  	c.scts = hs.serverHello.scts
 924  
 925  	if !hs.serverResumedSession() {
 926  		return false, nil
 927  	}
 928  
 929  	if hs.session.version != c.vers {
 930  		c.sendAlert(alertHandshakeFailure)
 931  		return false, errors.New("tls: server resumed a session with a different version")
 932  	}
 933  
 934  	if hs.session.cipherSuite != hs.suite.id {
 935  		c.sendAlert(alertHandshakeFailure)
 936  		return false, errors.New("tls: server resumed a session with a different cipher suite")
 937  	}
 938  
 939  	// RFC 7627, Section 5.3
 940  	if hs.session.extMasterSecret != hs.serverHello.extendedMasterSecret {
 941  		c.sendAlert(alertHandshakeFailure)
 942  		return false, errors.New("tls: server resumed a session with a different EMS extension")
 943  	}
 944  
 945  	// Restore master secret and certificates from previous state
 946  	hs.masterSecret = hs.session.secret
 947  	c.extMasterSecret = hs.session.extMasterSecret
 948  	c.peerCertificates = hs.session.peerCertificates
 949  	c.verifiedChains = hs.session.verifiedChains
 950  	c.ocspResponse = hs.session.ocspResponse
 951  	// Let the ServerHello SCTs override the session SCTs from the original
 952  	// connection, if any are provided.
 953  	if len(c.scts) == 0 && len(hs.session.scts) != 0 {
 954  		c.scts = hs.session.scts
 955  	}
 956  	c.curveID = hs.session.curveID
 957  
 958  	return true, nil
 959  }
 960  
 961  // checkALPN ensure that the server's choice of ALPN protocol is compatible with
 962  // the protocols that we advertised in the ClientHello.
 963  func checkALPN(clientProtos [][]byte, serverProto []byte, quic bool) error {
 964  	if serverProto == "" {
 965  		if quic && len(clientProtos) > 0 {
 966  			// RFC 9001, Section 8.1
 967  			return errors.New("tls: server did not select an ALPN protocol")
 968  		}
 969  		return nil
 970  	}
 971  	if len(clientProtos) == 0 {
 972  		return errors.New("tls: server advertised unrequested ALPN extension")
 973  	}
 974  	for _, proto := range clientProtos {
 975  		if proto == serverProto {
 976  			return nil
 977  		}
 978  	}
 979  	return errors.New("tls: server selected unadvertised ALPN protocol")
 980  }
 981  
 982  func (hs *clientHandshakeState) readFinished(out []byte) error {
 983  	c := hs.c
 984  
 985  	if err := c.readChangeCipherSpec(); err != nil {
 986  		return err
 987  	}
 988  
 989  	// finishedMsg is included in the transcript, but not until after we
 990  	// check the client version, since the state before this message was
 991  	// sent is used during verification.
 992  	msg, err := c.readHandshake(nil)
 993  	if err != nil {
 994  		return err
 995  	}
 996  	serverFinished, ok := msg.(*finishedMsg)
 997  	if !ok {
 998  		c.sendAlert(alertUnexpectedMessage)
 999  		return unexpectedMessageError(serverFinished, msg)
1000  	}
1001  
1002  	verify := hs.finishedHash.serverSum(hs.masterSecret)
1003  	if len(verify) != len(serverFinished.verifyData) ||
1004  		subtle.ConstantTimeCompare(verify, serverFinished.verifyData) != 1 {
1005  		c.sendAlert(alertHandshakeFailure)
1006  		return errors.New("tls: server's Finished message was incorrect")
1007  	}
1008  
1009  	if err := transcriptMsg(serverFinished, &hs.finishedHash); err != nil {
1010  		return err
1011  	}
1012  
1013  	copy(out, verify)
1014  	return nil
1015  }
1016  
1017  func (hs *clientHandshakeState) readSessionTicket() error {
1018  	if !hs.serverHello.ticketSupported {
1019  		return nil
1020  	}
1021  	c := hs.c
1022  
1023  	if !hs.hello.ticketSupported {
1024  		c.sendAlert(alertIllegalParameter)
1025  		return errors.New("tls: server sent unrequested session ticket")
1026  	}
1027  
1028  	msg, err := c.readHandshake(&hs.finishedHash)
1029  	if err != nil {
1030  		return err
1031  	}
1032  	sessionTicketMsg, ok := msg.(*newSessionTicketMsg)
1033  	if !ok {
1034  		c.sendAlert(alertUnexpectedMessage)
1035  		return unexpectedMessageError(sessionTicketMsg, msg)
1036  	}
1037  
1038  	hs.ticket = sessionTicketMsg.ticket
1039  	return nil
1040  }
1041  
1042  func (hs *clientHandshakeState) saveSessionTicket() error {
1043  	if hs.ticket == nil {
1044  		return nil
1045  	}
1046  	c := hs.c
1047  
1048  	cacheKey := c.clientSessionCacheKey()
1049  	if cacheKey == "" {
1050  		return nil
1051  	}
1052  
1053  	session := c.sessionState()
1054  	session.secret = hs.masterSecret
1055  	session.ticket = hs.ticket
1056  
1057  	cs := &ClientSessionState{session: session}
1058  	c.config.ClientSessionCache.Put(cacheKey, cs)
1059  	return nil
1060  }
1061  
1062  func (hs *clientHandshakeState) sendFinished(out []byte) error {
1063  	c := hs.c
1064  
1065  	if err := c.writeChangeCipherRecord(); err != nil {
1066  		return err
1067  	}
1068  
1069  	finished := &finishedMsg{}
1070  	finished.verifyData = hs.finishedHash.clientSum(hs.masterSecret)
1071  	if _, err := hs.c.writeHandshakeRecord(finished, &hs.finishedHash); err != nil {
1072  		return err
1073  	}
1074  	copy(out, finished.verifyData)
1075  	return nil
1076  }
1077  
1078  // defaultMaxRSAKeySize is the maximum RSA key size in bits that we are willing
1079  // to verify the signatures of during a TLS handshake.
1080  const defaultMaxRSAKeySize = 8192
1081  
1082  var tlsmaxrsasize = godebug.New("tlsmaxrsasize")
1083  
1084  func checkKeySize(n int) (max int, ok bool) {
1085  	if v := tlsmaxrsasize.Value(); v != "" {
1086  		if max, err := strconv.Atoi(v); err == nil {
1087  			if (n <= max) != (n <= defaultMaxRSAKeySize) {
1088  				tlsmaxrsasize.IncNonDefault()
1089  			}
1090  			return max, n <= max
1091  		}
1092  	}
1093  	return defaultMaxRSAKeySize, n <= defaultMaxRSAKeySize
1094  }
1095  
1096  // verifyServerCertificate parses and verifies the provided chain, setting
1097  // c.verifiedChains and c.peerCertificates or sending the appropriate alert.
1098  func (c *Conn) verifyServerCertificate(certificates [][]byte) error {
1099  	certs := []*x509.Certificate{:len(certificates)}
1100  	for i, asn1Data := range certificates {
1101  		cert, err := globalCertCache.newCert(asn1Data)
1102  		if err != nil {
1103  			c.sendAlert(alertDecodeError)
1104  			return errors.New("tls: failed to parse certificate from server: " + err.Error())
1105  		}
1106  		if cert.PublicKeyAlgorithm == x509.RSA {
1107  			n := cert.PublicKey.(*rsa.PublicKey).N.BitLen()
1108  			if max, ok := checkKeySize(n); !ok {
1109  				c.sendAlert(alertBadCertificate)
1110  				return fmt.Errorf("tls: server sent certificate containing RSA key larger than %d bits", max)
1111  			}
1112  		}
1113  		certs[i] = cert
1114  	}
1115  
1116  	echRejected := c.config.EncryptedClientHelloConfigList != nil && !c.echAccepted
1117  	if echRejected {
1118  		if c.config.EncryptedClientHelloRejectionVerify != nil {
1119  			if err := c.config.EncryptedClientHelloRejectionVerify(c.connectionStateLocked()); err != nil {
1120  				c.sendAlert(alertBadCertificate)
1121  				return err
1122  			}
1123  		} else {
1124  			opts := x509.VerifyOptions{
1125  				Roots:         c.config.RootCAs,
1126  				CurrentTime:   c.config.time(),
1127  				DNSName:       c.serverName,
1128  				Intermediates: x509.NewCertPool(),
1129  			}
1130  
1131  			for _, cert := range certs[1:] {
1132  				opts.Intermediates.AddCert(cert)
1133  			}
1134  			chains, err := certs[0].Verify(opts)
1135  			if err != nil {
1136  				c.sendAlert(alertBadCertificate)
1137  				return &CertificateVerificationError{UnverifiedCertificates: certs, Err: err}
1138  			}
1139  
1140  			c.verifiedChains, err = fipsAllowedChains(chains)
1141  			if err != nil {
1142  				c.sendAlert(alertBadCertificate)
1143  				return &CertificateVerificationError{UnverifiedCertificates: certs, Err: err}
1144  			}
1145  		}
1146  	} else if !c.config.InsecureSkipVerify {
1147  		opts := x509.VerifyOptions{
1148  			Roots:         c.config.RootCAs,
1149  			CurrentTime:   c.config.time(),
1150  			DNSName:       c.config.ServerName,
1151  			Intermediates: x509.NewCertPool(),
1152  		}
1153  
1154  		for _, cert := range certs[1:] {
1155  			opts.Intermediates.AddCert(cert)
1156  		}
1157  		chains, err := certs[0].Verify(opts)
1158  		if err != nil {
1159  			c.sendAlert(alertBadCertificate)
1160  			return &CertificateVerificationError{UnverifiedCertificates: certs, Err: err}
1161  		}
1162  
1163  		c.verifiedChains, err = fipsAllowedChains(chains)
1164  		if err != nil {
1165  			c.sendAlert(alertBadCertificate)
1166  			return &CertificateVerificationError{UnverifiedCertificates: certs, Err: err}
1167  		}
1168  	}
1169  
1170  	switch certs[0].PublicKey.(type) {
1171  	case *rsa.PublicKey, *ecdsa.PublicKey, ed25519.PublicKey:
1172  		break
1173  	default:
1174  		c.sendAlert(alertUnsupportedCertificate)
1175  		return fmt.Errorf("tls: server's certificate contains an unsupported type of public key: %T", certs[0].PublicKey)
1176  	}
1177  
1178  	c.peerCertificates = certs
1179  
1180  	if c.config.VerifyPeerCertificate != nil && !echRejected {
1181  		if err := c.config.VerifyPeerCertificate(certificates, c.verifiedChains); err != nil {
1182  			c.sendAlert(alertBadCertificate)
1183  			return err
1184  		}
1185  	}
1186  
1187  	if c.config.VerifyConnection != nil && !echRejected {
1188  		if err := c.config.VerifyConnection(c.connectionStateLocked()); err != nil {
1189  			c.sendAlert(alertBadCertificate)
1190  			return err
1191  		}
1192  	}
1193  
1194  	return nil
1195  }
1196  
1197  // certificateRequestInfoFromMsg generates a CertificateRequestInfo from a TLS
1198  // <= 1.2 CertificateRequest, making an effort to fill in missing information.
1199  func certificateRequestInfoFromMsg(ctx context.Context, vers uint16, certReq *certificateRequestMsg) *CertificateRequestInfo {
1200  	cri := &CertificateRequestInfo{
1201  		AcceptableCAs: certReq.certificateAuthorities,
1202  		Version:       vers,
1203  		ctx:           ctx,
1204  	}
1205  
1206  	var rsaAvail, ecAvail bool
1207  	for _, certType := range certReq.certificateTypes {
1208  		switch certType {
1209  		case certTypeRSASign:
1210  			rsaAvail = true
1211  		case certTypeECDSASign:
1212  			ecAvail = true
1213  		}
1214  	}
1215  
1216  	if !certReq.hasSignatureAlgorithm {
1217  		// Prior to TLS 1.2, signature schemes did not exist. In this case we
1218  		// make up a list based on the acceptable certificate types, to help
1219  		// GetClientCertificate and SupportsCertificate select the right certificate.
1220  		// The hash part of the SignatureScheme is a lie here, because
1221  		// TLS 1.0 and 1.1 always use MD5+SHA1 for RSA and SHA1 for ECDSA.
1222  		switch {
1223  		case rsaAvail && ecAvail:
1224  			cri.SignatureSchemes = []SignatureScheme{
1225  				ECDSAWithP256AndSHA256, ECDSAWithP384AndSHA384, ECDSAWithP521AndSHA512,
1226  				PKCS1WithSHA256, PKCS1WithSHA384, PKCS1WithSHA512, PKCS1WithSHA1,
1227  			}
1228  		case rsaAvail:
1229  			cri.SignatureSchemes = []SignatureScheme{
1230  				PKCS1WithSHA256, PKCS1WithSHA384, PKCS1WithSHA512, PKCS1WithSHA1,
1231  			}
1232  		case ecAvail:
1233  			cri.SignatureSchemes = []SignatureScheme{
1234  				ECDSAWithP256AndSHA256, ECDSAWithP384AndSHA384, ECDSAWithP521AndSHA512,
1235  			}
1236  		}
1237  		return cri
1238  	}
1239  
1240  	// Filter the signature schemes based on the certificate types.
1241  	// See RFC 5246, Section 7.4.4 (where it calls this "somewhat complicated").
1242  	cri.SignatureSchemes = []SignatureScheme{:0:len(certReq.supportedSignatureAlgorithms)}
1243  	for _, sigScheme := range certReq.supportedSignatureAlgorithms {
1244  		sigType, _, err := typeAndHashFromSignatureScheme(sigScheme)
1245  		if err != nil {
1246  			continue
1247  		}
1248  		switch sigType {
1249  		case signatureECDSA, signatureEd25519:
1250  			if ecAvail {
1251  				cri.SignatureSchemes = append(cri.SignatureSchemes, sigScheme)
1252  			}
1253  		case signatureRSAPSS, signaturePKCS1v15:
1254  			if rsaAvail {
1255  				cri.SignatureSchemes = append(cri.SignatureSchemes, sigScheme)
1256  			}
1257  		}
1258  	}
1259  
1260  	return cri
1261  }
1262  
1263  func (c *Conn) getClientCertificate(cri *CertificateRequestInfo) (*Certificate, error) {
1264  	if c.config.GetClientCertificate != nil {
1265  		return c.config.GetClientCertificate(cri)
1266  	}
1267  
1268  	for _, chain := range c.config.Certificates {
1269  		if err := cri.SupportsCertificate(&chain); err != nil {
1270  			continue
1271  		}
1272  		return &chain, nil
1273  	}
1274  
1275  	// No acceptable certificate found. Don't send a certificate.
1276  	return &Certificate{}, nil
1277  }
1278  
1279  // clientSessionCacheKey returns a key used to cache sessionTickets that could
1280  // be used to resume previously negotiated TLS sessions with a server.
1281  func (c *Conn) clientSessionCacheKey() []byte {
1282  	if len(c.config.ServerName) > 0 {
1283  		return c.config.ServerName
1284  	}
1285  	if c.conn != nil {
1286  		return c.conn.RemoteAddr().String()
1287  	}
1288  	return ""
1289  }
1290  
1291  // hostnameInSNI converts name into an appropriate hostname for SNI.
1292  // Literal IP addresses and absolute FQDNs are not permitted as SNI values.
1293  // See RFC 6066, Section 3.
1294  func hostnameInSNI(name []byte) []byte {
1295  	host := name
1296  	if len(host) > 0 && host[0] == '[' && host[len(host)-1] == ']' {
1297  		host = host[1 : len(host)-1]
1298  	}
1299  	if i := bytes.LastIndex(host, "%"); i > 0 {
1300  		host = host[:i]
1301  	}
1302  	if net.ParseIP(host) != nil {
1303  		return ""
1304  	}
1305  	for len(name) > 0 && name[len(name)-1] == '.' {
1306  		name = name[:len(name)-1]
1307  	}
1308  	return name
1309  }
1310  
1311  func computeAndUpdatePSK(m *clientHelloMsg, binderKey []byte, transcript hash.Hash, finishedHash func([]byte, hash.Hash) []byte) error {
1312  	helloBytes, err := m.marshalWithoutBinders()
1313  	if err != nil {
1314  		return err
1315  	}
1316  	transcript.Write(helloBytes)
1317  	pskBinders := [][]byte{finishedHash(binderKey, transcript)}
1318  	return m.updateBinders(pskBinders)
1319  }
1320