Source file src/crypto/tls/handshake_client.go

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

View as plain text