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

View as plain text