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

View as plain text