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

View as plain text