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  	if chainToSend != nil {
   732  		hs.c.localCertificate = chainToSend.Certificate
   733  	}
   734  
   735  	shd, ok := msg.(*serverHelloDoneMsg)
   736  	if !ok {
   737  		c.sendAlert(alertUnexpectedMessage)
   738  		return unexpectedMessageError(shd, msg)
   739  	}
   740  
   741  	// If the server requested a certificate then we have to send a
   742  	// Certificate message, even if it's empty because we don't have a
   743  	// certificate to send.
   744  	if certRequested {
   745  		certMsg = new(certificateMsg)
   746  		certMsg.certificates = chainToSend.Certificate
   747  		if _, err := hs.c.writeHandshakeRecord(certMsg, &hs.finishedHash); err != nil {
   748  			return err
   749  		}
   750  	}
   751  
   752  	preMasterSecret, ckx, err := keyAgreement.generateClientKeyExchange(c.config, hs.hello, c.peerCertificates[0])
   753  	if err != nil {
   754  		c.sendAlert(alertInternalError)
   755  		return err
   756  	}
   757  	if ckx != nil {
   758  		if _, err := hs.c.writeHandshakeRecord(ckx, &hs.finishedHash); err != nil {
   759  			return err
   760  		}
   761  	}
   762  
   763  	if hs.serverHello.extendedMasterSecret {
   764  		c.extMasterSecret = true
   765  		hs.masterSecret = extMasterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret,
   766  			hs.finishedHash.Sum())
   767  	} else {
   768  		if fips140tls.Required() {
   769  			c.sendAlert(alertHandshakeFailure)
   770  			return errors.New("tls: FIPS 140-3 requires the use of Extended Master Secret")
   771  		}
   772  		hs.masterSecret = masterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret,
   773  			hs.hello.random, hs.serverHello.random)
   774  	}
   775  	if err := c.config.writeKeyLog(keyLogLabelTLS12, hs.hello.random, hs.masterSecret); err != nil {
   776  		c.sendAlert(alertInternalError)
   777  		return errors.New("tls: failed to write to key log: " + err.Error())
   778  	}
   779  
   780  	if chainToSend != nil && len(chainToSend.Certificate) > 0 {
   781  		certVerify := &certificateVerifyMsg{}
   782  
   783  		key, ok := chainToSend.PrivateKey.(crypto.Signer)
   784  		if !ok {
   785  			c.sendAlert(alertInternalError)
   786  			return fmt.Errorf("tls: client certificate private key of type %T does not implement crypto.Signer", chainToSend.PrivateKey)
   787  		}
   788  
   789  		if c.vers >= VersionTLS12 {
   790  			signatureAlgorithm, err := selectSignatureScheme(c.vers, chainToSend, certReq.supportedSignatureAlgorithms)
   791  			if err != nil {
   792  				c.sendAlert(alertHandshakeFailure)
   793  				return err
   794  			}
   795  			sigType, sigHash, err := typeAndHashFromSignatureScheme(signatureAlgorithm)
   796  			if err != nil {
   797  				return c.sendAlert(alertInternalError)
   798  			}
   799  			certVerify.hasSignatureAlgorithm = true
   800  			certVerify.signatureAlgorithm = signatureAlgorithm
   801  			if sigHash == crypto.SHA1 {
   802  				tlssha1.Value() // ensure godebug is initialized
   803  				tlssha1.IncNonDefault()
   804  			}
   805  			if hs.finishedHash.buffer == nil {
   806  				c.sendAlert(alertInternalError)
   807  				return errors.New("tls: internal error: did not keep handshake transcript for TLS 1.2")
   808  			}
   809  			signOpts := crypto.SignerOpts(sigHash)
   810  			if sigType == signatureRSAPSS {
   811  				signOpts = &rsa.PSSOptions{SaltLength: rsa.PSSSaltLengthEqualsHash, Hash: sigHash}
   812  			}
   813  			certVerify.signature, err = crypto.SignMessage(key, c.config.rand(), hs.finishedHash.buffer, signOpts)
   814  			if err != nil {
   815  				c.sendAlert(alertInternalError)
   816  				return err
   817  			}
   818  		} else {
   819  			sigType, sigHash, err := legacyTypeAndHashFromPublicKey(key.Public())
   820  			if err != nil {
   821  				c.sendAlert(alertIllegalParameter)
   822  				return err
   823  			}
   824  			signed := hs.finishedHash.hashForClientCertificate(sigType)
   825  			certVerify.signature, err = key.Sign(c.config.rand(), signed, sigHash)
   826  			if err != nil {
   827  				c.sendAlert(alertInternalError)
   828  				return err
   829  			}
   830  		}
   831  
   832  		if _, err := hs.c.writeHandshakeRecord(certVerify, &hs.finishedHash); err != nil {
   833  			return err
   834  		}
   835  	}
   836  
   837  	hs.finishedHash.discardHandshakeBuffer()
   838  
   839  	return nil
   840  }
   841  
   842  func (hs *clientHandshakeState) establishKeys() error {
   843  	c := hs.c
   844  
   845  	clientMAC, serverMAC, clientKey, serverKey, clientIV, serverIV :=
   846  		keysFromMasterSecret(c.vers, hs.suite, hs.masterSecret, hs.hello.random, hs.serverHello.random, hs.suite.macLen, hs.suite.keyLen, hs.suite.ivLen)
   847  	var clientCipher, serverCipher any
   848  	var clientHash, serverHash hash.Hash
   849  	if hs.suite.cipher != nil {
   850  		clientCipher = hs.suite.cipher(clientKey, clientIV, false /* not for reading */)
   851  		clientHash = hs.suite.mac(clientMAC)
   852  		serverCipher = hs.suite.cipher(serverKey, serverIV, true /* for reading */)
   853  		serverHash = hs.suite.mac(serverMAC)
   854  	} else {
   855  		clientCipher = hs.suite.aead(clientKey, clientIV)
   856  		serverCipher = hs.suite.aead(serverKey, serverIV)
   857  	}
   858  
   859  	c.in.prepareCipherSpec(c.vers, serverCipher, serverHash)
   860  	c.out.prepareCipherSpec(c.vers, clientCipher, clientHash)
   861  	return nil
   862  }
   863  
   864  func (hs *clientHandshakeState) serverResumedSession() bool {
   865  	// If the server responded with the same sessionId then it means the
   866  	// sessionTicket is being used to resume a TLS session.
   867  	return hs.session != nil && hs.hello.sessionId != nil &&
   868  		bytes.Equal(hs.serverHello.sessionId, hs.hello.sessionId)
   869  }
   870  
   871  func (hs *clientHandshakeState) processServerHello() (bool, error) {
   872  	c := hs.c
   873  
   874  	if err := hs.pickCipherSuite(); err != nil {
   875  		return false, err
   876  	}
   877  
   878  	if hs.serverHello.compressionMethod != compressionNone {
   879  		c.sendAlert(alertIllegalParameter)
   880  		return false, errors.New("tls: server selected unsupported compression format")
   881  	}
   882  
   883  	supportsPointFormat := false
   884  	offeredNonCompressedFormat := false
   885  	for _, format := range hs.serverHello.supportedPoints {
   886  		if format == pointFormatUncompressed {
   887  			supportsPointFormat = true
   888  		} else {
   889  			offeredNonCompressedFormat = true
   890  		}
   891  	}
   892  	if !supportsPointFormat && offeredNonCompressedFormat {
   893  		return false, errors.New("tls: server offered only incompatible point formats")
   894  	}
   895  
   896  	if c.handshakes == 0 && hs.serverHello.secureRenegotiationSupported {
   897  		c.secureRenegotiation = true
   898  		if len(hs.serverHello.secureRenegotiation) != 0 {
   899  			c.sendAlert(alertHandshakeFailure)
   900  			return false, errors.New("tls: initial handshake had non-empty renegotiation extension")
   901  		}
   902  	}
   903  
   904  	if c.handshakes > 0 && c.secureRenegotiation {
   905  		var expectedSecureRenegotiation [24]byte
   906  		copy(expectedSecureRenegotiation[:], c.clientFinished[:])
   907  		copy(expectedSecureRenegotiation[12:], c.serverFinished[:])
   908  		if !bytes.Equal(hs.serverHello.secureRenegotiation, expectedSecureRenegotiation[:]) {
   909  			c.sendAlert(alertHandshakeFailure)
   910  			return false, errors.New("tls: incorrect renegotiation extension contents")
   911  		}
   912  	}
   913  
   914  	if err := checkALPN(hs.hello.alpnProtocols, hs.serverHello.alpnProtocol, false); err != nil {
   915  		c.sendAlert(alertUnsupportedExtension)
   916  		return false, err
   917  	}
   918  	c.clientProtocol = hs.serverHello.alpnProtocol
   919  
   920  	c.scts = hs.serverHello.scts
   921  
   922  	if !hs.serverResumedSession() {
   923  		return false, nil
   924  	}
   925  
   926  	if hs.session.version != c.vers {
   927  		c.sendAlert(alertHandshakeFailure)
   928  		return false, errors.New("tls: server resumed a session with a different version")
   929  	}
   930  
   931  	if hs.session.cipherSuite != hs.suite.id {
   932  		c.sendAlert(alertHandshakeFailure)
   933  		return false, errors.New("tls: server resumed a session with a different cipher suite")
   934  	}
   935  
   936  	// RFC 7627, Section 5.3
   937  	if hs.session.extMasterSecret != hs.serverHello.extendedMasterSecret {
   938  		c.sendAlert(alertHandshakeFailure)
   939  		return false, errors.New("tls: server resumed a session with a different EMS extension")
   940  	}
   941  
   942  	// Restore master secret and certificates from previous state
   943  	hs.masterSecret = hs.session.secret
   944  	c.extMasterSecret = hs.session.extMasterSecret
   945  	c.peerCertificates = hs.session.peerCertificates
   946  	c.verifiedChains = hs.session.verifiedChains
   947  	c.ocspResponse = hs.session.ocspResponse
   948  	// Let the ServerHello SCTs override the session SCTs from the original
   949  	// connection, if any are provided.
   950  	if len(c.scts) == 0 && len(hs.session.scts) != 0 {
   951  		c.scts = hs.session.scts
   952  	}
   953  	c.curveID = hs.session.curveID
   954  
   955  	return true, nil
   956  }
   957  
   958  // checkALPN ensure that the server's choice of ALPN protocol is compatible with
   959  // the protocols that we advertised in the ClientHello.
   960  func checkALPN(clientProtos []string, serverProto string, quic bool) error {
   961  	if serverProto == "" {
   962  		if quic && len(clientProtos) > 0 {
   963  			// RFC 9001, Section 8.1
   964  			return errors.New("tls: server did not select an ALPN protocol")
   965  		}
   966  		return nil
   967  	}
   968  	if len(clientProtos) == 0 {
   969  		return errors.New("tls: server advertised unrequested ALPN extension")
   970  	}
   971  	for _, proto := range clientProtos {
   972  		if proto == serverProto {
   973  			return nil
   974  		}
   975  	}
   976  	return errors.New("tls: server selected unadvertised ALPN protocol")
   977  }
   978  
   979  func (hs *clientHandshakeState) readFinished(out []byte) error {
   980  	c := hs.c
   981  
   982  	if err := c.readChangeCipherSpec(); err != nil {
   983  		return err
   984  	}
   985  
   986  	// finishedMsg is included in the transcript, but not until after we
   987  	// check the client version, since the state before this message was
   988  	// sent is used during verification.
   989  	msg, err := c.readHandshake(nil)
   990  	if err != nil {
   991  		return err
   992  	}
   993  	serverFinished, ok := msg.(*finishedMsg)
   994  	if !ok {
   995  		c.sendAlert(alertUnexpectedMessage)
   996  		return unexpectedMessageError(serverFinished, msg)
   997  	}
   998  
   999  	verify := hs.finishedHash.serverSum(hs.masterSecret)
  1000  	if len(verify) != len(serverFinished.verifyData) ||
  1001  		subtle.ConstantTimeCompare(verify, serverFinished.verifyData) != 1 {
  1002  		c.sendAlert(alertHandshakeFailure)
  1003  		return errors.New("tls: server's Finished message was incorrect")
  1004  	}
  1005  
  1006  	if err := transcriptMsg(serverFinished, &hs.finishedHash); err != nil {
  1007  		return err
  1008  	}
  1009  
  1010  	copy(out, verify)
  1011  	return nil
  1012  }
  1013  
  1014  func (hs *clientHandshakeState) readSessionTicket() error {
  1015  	if !hs.serverHello.ticketSupported {
  1016  		return nil
  1017  	}
  1018  	c := hs.c
  1019  
  1020  	if !hs.hello.ticketSupported {
  1021  		c.sendAlert(alertIllegalParameter)
  1022  		return errors.New("tls: server sent unrequested session ticket")
  1023  	}
  1024  
  1025  	msg, err := c.readHandshake(&hs.finishedHash)
  1026  	if err != nil {
  1027  		return err
  1028  	}
  1029  	sessionTicketMsg, ok := msg.(*newSessionTicketMsg)
  1030  	if !ok {
  1031  		c.sendAlert(alertUnexpectedMessage)
  1032  		return unexpectedMessageError(sessionTicketMsg, msg)
  1033  	}
  1034  
  1035  	hs.ticket = sessionTicketMsg.ticket
  1036  	return nil
  1037  }
  1038  
  1039  func (hs *clientHandshakeState) saveSessionTicket() error {
  1040  	if hs.ticket == nil {
  1041  		return nil
  1042  	}
  1043  	c := hs.c
  1044  
  1045  	cacheKey := c.clientSessionCacheKey()
  1046  	if cacheKey == "" {
  1047  		return nil
  1048  	}
  1049  
  1050  	session := c.sessionState()
  1051  	session.secret = hs.masterSecret
  1052  	session.ticket = hs.ticket
  1053  
  1054  	cs := &ClientSessionState{session: session}
  1055  	c.config.ClientSessionCache.Put(cacheKey, cs)
  1056  	return nil
  1057  }
  1058  
  1059  func (hs *clientHandshakeState) sendFinished(out []byte) error {
  1060  	c := hs.c
  1061  
  1062  	if err := c.writeChangeCipherRecord(); err != nil {
  1063  		return err
  1064  	}
  1065  
  1066  	finished := new(finishedMsg)
  1067  	finished.verifyData = hs.finishedHash.clientSum(hs.masterSecret)
  1068  	if _, err := hs.c.writeHandshakeRecord(finished, &hs.finishedHash); err != nil {
  1069  		return err
  1070  	}
  1071  	copy(out, finished.verifyData)
  1072  	return nil
  1073  }
  1074  
  1075  // defaultMaxRSAKeySize is the maximum RSA key size in bits that we are willing
  1076  // to verify the signatures of during a TLS handshake.
  1077  const defaultMaxRSAKeySize = 8192
  1078  
  1079  var tlsmaxrsasize = godebug.New("tlsmaxrsasize")
  1080  
  1081  func checkKeySize(n int) (max int, ok bool) {
  1082  	if v := tlsmaxrsasize.Value(); v != "" {
  1083  		if max, err := strconv.Atoi(v); err == nil {
  1084  			if (n <= max) != (n <= defaultMaxRSAKeySize) {
  1085  				tlsmaxrsasize.IncNonDefault()
  1086  			}
  1087  			return max, n <= max
  1088  		}
  1089  	}
  1090  	return defaultMaxRSAKeySize, n <= defaultMaxRSAKeySize
  1091  }
  1092  
  1093  // verifyServerCertificate parses and verifies the provided chain, setting
  1094  // c.verifiedChains and c.peerCertificates or sending the appropriate alert.
  1095  func (c *Conn) verifyServerCertificate(certificates [][]byte) error {
  1096  	certs := make([]*x509.Certificate, len(certificates))
  1097  	for i, asn1Data := range certificates {
  1098  		cert, err := globalCertCache.newCert(asn1Data)
  1099  		if err != nil {
  1100  			c.sendAlert(alertDecodeError)
  1101  			return errors.New("tls: failed to parse certificate from server: " + err.Error())
  1102  		}
  1103  		if cert.PublicKeyAlgorithm == x509.RSA {
  1104  			n := cert.PublicKey.(*rsa.PublicKey).N.BitLen()
  1105  			if max, ok := checkKeySize(n); !ok {
  1106  				c.sendAlert(alertBadCertificate)
  1107  				return fmt.Errorf("tls: server sent certificate containing RSA key larger than %d bits", max)
  1108  			}
  1109  		}
  1110  		certs[i] = cert
  1111  	}
  1112  
  1113  	echRejected := c.config.EncryptedClientHelloConfigList != nil && !c.echAccepted
  1114  	if echRejected {
  1115  		if c.config.EncryptedClientHelloRejectionVerify != nil {
  1116  			if err := c.config.EncryptedClientHelloRejectionVerify(c.connectionStateLocked()); err != nil {
  1117  				c.sendAlert(alertBadCertificate)
  1118  				return err
  1119  			}
  1120  		} else {
  1121  			opts := x509.VerifyOptions{
  1122  				Roots:         c.config.RootCAs,
  1123  				CurrentTime:   c.config.time(),
  1124  				DNSName:       c.serverName,
  1125  				Intermediates: x509.NewCertPool(),
  1126  			}
  1127  
  1128  			for _, cert := range certs[1:] {
  1129  				opts.Intermediates.AddCert(cert)
  1130  			}
  1131  			chains, err := certs[0].Verify(opts)
  1132  			if err != nil {
  1133  				c.sendAlert(alertBadCertificate)
  1134  				return &CertificateVerificationError{UnverifiedCertificates: certs, Err: err}
  1135  			}
  1136  
  1137  			c.verifiedChains, err = fipsAllowedChains(chains)
  1138  			if err != nil {
  1139  				c.sendAlert(alertBadCertificate)
  1140  				return &CertificateVerificationError{UnverifiedCertificates: certs, Err: err}
  1141  			}
  1142  		}
  1143  	} else if !c.config.InsecureSkipVerify {
  1144  		opts := x509.VerifyOptions{
  1145  			Roots:         c.config.RootCAs,
  1146  			CurrentTime:   c.config.time(),
  1147  			DNSName:       c.config.ServerName,
  1148  			Intermediates: x509.NewCertPool(),
  1149  		}
  1150  
  1151  		for _, cert := range certs[1:] {
  1152  			opts.Intermediates.AddCert(cert)
  1153  		}
  1154  		chains, err := certs[0].Verify(opts)
  1155  		if err != nil {
  1156  			c.sendAlert(alertBadCertificate)
  1157  			return &CertificateVerificationError{UnverifiedCertificates: certs, Err: err}
  1158  		}
  1159  
  1160  		c.verifiedChains, err = fipsAllowedChains(chains)
  1161  		if err != nil {
  1162  			c.sendAlert(alertBadCertificate)
  1163  			return &CertificateVerificationError{UnverifiedCertificates: certs, Err: err}
  1164  		}
  1165  	}
  1166  
  1167  	switch certs[0].PublicKey.(type) {
  1168  	case *rsa.PublicKey, *ecdsa.PublicKey, ed25519.PublicKey:
  1169  	case *mldsa.PublicKey:
  1170  		if c.vers < VersionTLS13 {
  1171  			c.sendAlert(alertIllegalParameter)
  1172  			return errors.New("tls: server's certificate uses ML-DSA, which requires TLS 1.3")
  1173  		}
  1174  	default:
  1175  		c.sendAlert(alertUnsupportedCertificate)
  1176  		return fmt.Errorf("tls: server's certificate contains an unsupported type of public key: %T", certs[0].PublicKey)
  1177  	}
  1178  
  1179  	c.peerCertificates = certs
  1180  
  1181  	if c.config.VerifyPeerCertificate != nil && !echRejected {
  1182  		if err := c.config.VerifyPeerCertificate(certificates, c.verifiedChains); err != nil {
  1183  			c.sendAlert(alertBadCertificate)
  1184  			return err
  1185  		}
  1186  	}
  1187  
  1188  	if c.config.VerifyConnection != nil && !echRejected {
  1189  		if err := c.config.VerifyConnection(c.connectionStateLocked()); err != nil {
  1190  			c.sendAlert(alertBadCertificate)
  1191  			return err
  1192  		}
  1193  	}
  1194  
  1195  	return nil
  1196  }
  1197  
  1198  // certificateRequestInfoFromMsg generates a CertificateRequestInfo from a TLS
  1199  // <= 1.2 CertificateRequest, making an effort to fill in missing information.
  1200  func certificateRequestInfoFromMsg(ctx context.Context, vers uint16, certReq *certificateRequestMsg) *CertificateRequestInfo {
  1201  	cri := &CertificateRequestInfo{
  1202  		AcceptableCAs: certReq.certificateAuthorities,
  1203  		Version:       vers,
  1204  		ctx:           ctx,
  1205  	}
  1206  
  1207  	var rsaAvail, ecAvail bool
  1208  	for _, certType := range certReq.certificateTypes {
  1209  		switch certType {
  1210  		case certTypeRSASign:
  1211  			rsaAvail = true
  1212  		case certTypeECDSASign:
  1213  			ecAvail = true
  1214  		}
  1215  	}
  1216  
  1217  	if !certReq.hasSignatureAlgorithm {
  1218  		// Prior to TLS 1.2, signature schemes did not exist. In this case we
  1219  		// make up a list based on the acceptable certificate types, to help
  1220  		// GetClientCertificate and SupportsCertificate select the right certificate.
  1221  		// The hash part of the SignatureScheme is a lie here, because
  1222  		// TLS 1.0 and 1.1 always use MD5+SHA1 for RSA and SHA1 for ECDSA.
  1223  		switch {
  1224  		case rsaAvail && ecAvail:
  1225  			cri.SignatureSchemes = []SignatureScheme{
  1226  				ECDSAWithP256AndSHA256, ECDSAWithP384AndSHA384, ECDSAWithP521AndSHA512,
  1227  				PKCS1WithSHA256, PKCS1WithSHA384, PKCS1WithSHA512, PKCS1WithSHA1,
  1228  			}
  1229  		case rsaAvail:
  1230  			cri.SignatureSchemes = []SignatureScheme{
  1231  				PKCS1WithSHA256, PKCS1WithSHA384, PKCS1WithSHA512, PKCS1WithSHA1,
  1232  			}
  1233  		case ecAvail:
  1234  			cri.SignatureSchemes = []SignatureScheme{
  1235  				ECDSAWithP256AndSHA256, ECDSAWithP384AndSHA384, ECDSAWithP521AndSHA512,
  1236  			}
  1237  		}
  1238  		return cri
  1239  	}
  1240  
  1241  	// Filter the signature schemes based on the certificate types.
  1242  	// See RFC 5246, Section 7.4.4 (where it calls this "somewhat complicated").
  1243  	cri.SignatureSchemes = make([]SignatureScheme, 0, len(certReq.supportedSignatureAlgorithms))
  1244  	for _, sigScheme := range certReq.supportedSignatureAlgorithms {
  1245  		sigType, _, err := typeAndHashFromSignatureScheme(sigScheme)
  1246  		if err != nil {
  1247  			continue
  1248  		}
  1249  		switch sigType {
  1250  		case signatureECDSA, signatureEd25519:
  1251  			if ecAvail {
  1252  				cri.SignatureSchemes = append(cri.SignatureSchemes, sigScheme)
  1253  			}
  1254  		case signatureRSAPSS, signaturePKCS1v15:
  1255  			if rsaAvail {
  1256  				cri.SignatureSchemes = append(cri.SignatureSchemes, sigScheme)
  1257  			}
  1258  		}
  1259  	}
  1260  
  1261  	return cri
  1262  }
  1263  
  1264  func (c *Conn) getClientCertificate(cri *CertificateRequestInfo) (*Certificate, error) {
  1265  	if c.config.GetClientCertificate != nil {
  1266  		return c.config.GetClientCertificate(cri)
  1267  	}
  1268  
  1269  	for _, chain := range c.config.Certificates {
  1270  		if err := cri.SupportsCertificate(&chain); err != nil {
  1271  			continue
  1272  		}
  1273  		return &chain, nil
  1274  	}
  1275  
  1276  	// No acceptable certificate found. Don't send a certificate.
  1277  	return new(Certificate), nil
  1278  }
  1279  
  1280  // clientSessionCacheKey returns a key used to cache sessionTickets that could
  1281  // be used to resume previously negotiated TLS sessions with a server.
  1282  func (c *Conn) clientSessionCacheKey() string {
  1283  	if len(c.config.ServerName) > 0 {
  1284  		return c.config.ServerName
  1285  	}
  1286  	if c.conn != nil {
  1287  		return c.conn.RemoteAddr().String()
  1288  	}
  1289  	return ""
  1290  }
  1291  
  1292  // hostnameInSNI converts name into an appropriate hostname for SNI.
  1293  // Literal IP addresses and absolute FQDNs are not permitted as SNI values.
  1294  // See RFC 6066, Section 3.
  1295  func hostnameInSNI(name string) string {
  1296  	host := name
  1297  	if len(host) > 0 && host[0] == '[' && host[len(host)-1] == ']' {
  1298  		host = host[1 : len(host)-1]
  1299  	}
  1300  	if i := strings.LastIndex(host, "%"); i > 0 {
  1301  		host = host[:i]
  1302  	}
  1303  	if net.ParseIP(host) != nil {
  1304  		return ""
  1305  	}
  1306  	for len(name) > 0 && name[len(name)-1] == '.' {
  1307  		name = name[:len(name)-1]
  1308  	}
  1309  	return name
  1310  }
  1311  
  1312  func computeAndUpdatePSK(m *clientHelloMsg, binderKey []byte, transcript hash.Hash, finishedHash func([]byte, hash.Hash) []byte) error {
  1313  	helloBytes, err := m.marshalWithoutBinders()
  1314  	if err != nil {
  1315  		return err
  1316  	}
  1317  	transcript.Write(helloBytes)
  1318  	pskBinders := [][]byte{finishedHash(binderKey, transcript)}
  1319  	return m.updateBinders(pskBinders)
  1320  }
  1321  

View as plain text