Source file src/crypto/tls/handshake_client.go

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

View as plain text