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

View as plain text