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

View as plain text