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

View as plain text