Source file src/crypto/tls/handshake_client.go

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

View as plain text