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

View as plain text