Source file src/crypto/tls/handshake_client.go

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