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

View as plain text