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  	if hs.c.config.CipherSuites == nil && rsaKexCiphers[hs.suite.id] {
   530  		tlsrsakex.IncNonDefault()
   531  	}
   532  
   533  	hs.c.cipherSuite = hs.suite.id
   534  	return nil
   535  }
   536  
   537  func (hs *clientHandshakeState) doFullHandshake() error {
   538  	c := hs.c
   539  
   540  	msg, err := c.readHandshake(&hs.finishedHash)
   541  	if err != nil {
   542  		return err
   543  	}
   544  	certMsg, ok := msg.(*certificateMsg)
   545  	if !ok || len(certMsg.certificates) == 0 {
   546  		c.sendAlert(alertUnexpectedMessage)
   547  		return unexpectedMessageError(certMsg, msg)
   548  	}
   549  
   550  	msg, err = c.readHandshake(&hs.finishedHash)
   551  	if err != nil {
   552  		return err
   553  	}
   554  
   555  	cs, ok := msg.(*certificateStatusMsg)
   556  	if ok {
   557  		// RFC4366 on Certificate Status Request:
   558  		// The server MAY return a "certificate_status" message.
   559  
   560  		if !hs.serverHello.ocspStapling {
   561  			// If a server returns a "CertificateStatus" message, then the
   562  			// server MUST have included an extension of type "status_request"
   563  			// with empty "extension_data" in the extended server hello.
   564  
   565  			c.sendAlert(alertUnexpectedMessage)
   566  			return errors.New("tls: received unexpected CertificateStatus message")
   567  		}
   568  
   569  		c.ocspResponse = cs.response
   570  
   571  		msg, err = c.readHandshake(&hs.finishedHash)
   572  		if err != nil {
   573  			return err
   574  		}
   575  	}
   576  
   577  	if c.handshakes == 0 {
   578  		// If this is the first handshake on a connection, process and
   579  		// (optionally) verify the server's certificates.
   580  		if err := c.verifyServerCertificate(certMsg.certificates); err != nil {
   581  			return err
   582  		}
   583  	} else {
   584  		// This is a renegotiation handshake. We require that the
   585  		// server's identity (i.e. leaf certificate) is unchanged and
   586  		// thus any previous trust decision is still valid.
   587  		//
   588  		// See https://mitls.org/pages/attacks/3SHAKE for the
   589  		// motivation behind this requirement.
   590  		if !bytes.Equal(c.peerCertificates[0].Raw, certMsg.certificates[0]) {
   591  			c.sendAlert(alertBadCertificate)
   592  			return errors.New("tls: server's identity changed during renegotiation")
   593  		}
   594  	}
   595  
   596  	keyAgreement := hs.suite.ka(c.vers)
   597  
   598  	skx, ok := msg.(*serverKeyExchangeMsg)
   599  	if ok {
   600  		err = keyAgreement.processServerKeyExchange(c.config, hs.hello, hs.serverHello, c.peerCertificates[0], skx)
   601  		if err != nil {
   602  			c.sendAlert(alertUnexpectedMessage)
   603  			return err
   604  		}
   605  
   606  		msg, err = c.readHandshake(&hs.finishedHash)
   607  		if err != nil {
   608  			return err
   609  		}
   610  	}
   611  
   612  	var chainToSend *Certificate
   613  	var certRequested bool
   614  	certReq, ok := msg.(*certificateRequestMsg)
   615  	if ok {
   616  		certRequested = true
   617  
   618  		cri := certificateRequestInfoFromMsg(hs.ctx, c.vers, certReq)
   619  		if chainToSend, err = c.getClientCertificate(cri); err != nil {
   620  			c.sendAlert(alertInternalError)
   621  			return err
   622  		}
   623  
   624  		msg, err = c.readHandshake(&hs.finishedHash)
   625  		if err != nil {
   626  			return err
   627  		}
   628  	}
   629  
   630  	shd, ok := msg.(*serverHelloDoneMsg)
   631  	if !ok {
   632  		c.sendAlert(alertUnexpectedMessage)
   633  		return unexpectedMessageError(shd, msg)
   634  	}
   635  
   636  	// If the server requested a certificate then we have to send a
   637  	// Certificate message, even if it's empty because we don't have a
   638  	// certificate to send.
   639  	if certRequested {
   640  		certMsg = new(certificateMsg)
   641  		certMsg.certificates = chainToSend.Certificate
   642  		if _, err := hs.c.writeHandshakeRecord(certMsg, &hs.finishedHash); err != nil {
   643  			return err
   644  		}
   645  	}
   646  
   647  	preMasterSecret, ckx, err := keyAgreement.generateClientKeyExchange(c.config, hs.hello, c.peerCertificates[0])
   648  	if err != nil {
   649  		c.sendAlert(alertInternalError)
   650  		return err
   651  	}
   652  	if ckx != nil {
   653  		if _, err := hs.c.writeHandshakeRecord(ckx, &hs.finishedHash); err != nil {
   654  			return err
   655  		}
   656  	}
   657  
   658  	if hs.serverHello.extendedMasterSecret {
   659  		c.extMasterSecret = true
   660  		hs.masterSecret = extMasterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret,
   661  			hs.finishedHash.Sum())
   662  	} else {
   663  		hs.masterSecret = masterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret,
   664  			hs.hello.random, hs.serverHello.random)
   665  	}
   666  	if err := c.config.writeKeyLog(keyLogLabelTLS12, hs.hello.random, hs.masterSecret); err != nil {
   667  		c.sendAlert(alertInternalError)
   668  		return errors.New("tls: failed to write to key log: " + err.Error())
   669  	}
   670  
   671  	if chainToSend != nil && len(chainToSend.Certificate) > 0 {
   672  		certVerify := &certificateVerifyMsg{}
   673  
   674  		key, ok := chainToSend.PrivateKey.(crypto.Signer)
   675  		if !ok {
   676  			c.sendAlert(alertInternalError)
   677  			return fmt.Errorf("tls: client certificate private key of type %T does not implement crypto.Signer", chainToSend.PrivateKey)
   678  		}
   679  
   680  		var sigType uint8
   681  		var sigHash crypto.Hash
   682  		if c.vers >= VersionTLS12 {
   683  			signatureAlgorithm, err := selectSignatureScheme(c.vers, chainToSend, certReq.supportedSignatureAlgorithms)
   684  			if err != nil {
   685  				c.sendAlert(alertIllegalParameter)
   686  				return err
   687  			}
   688  			sigType, sigHash, err = typeAndHashFromSignatureScheme(signatureAlgorithm)
   689  			if err != nil {
   690  				return c.sendAlert(alertInternalError)
   691  			}
   692  			certVerify.hasSignatureAlgorithm = true
   693  			certVerify.signatureAlgorithm = signatureAlgorithm
   694  		} else {
   695  			sigType, sigHash, err = legacyTypeAndHashFromPublicKey(key.Public())
   696  			if err != nil {
   697  				c.sendAlert(alertIllegalParameter)
   698  				return err
   699  			}
   700  		}
   701  
   702  		signed := hs.finishedHash.hashForClientCertificate(sigType, sigHash)
   703  		signOpts := crypto.SignerOpts(sigHash)
   704  		if sigType == signatureRSAPSS {
   705  			signOpts = &rsa.PSSOptions{SaltLength: rsa.PSSSaltLengthEqualsHash, Hash: sigHash}
   706  		}
   707  		certVerify.signature, err = key.Sign(c.config.rand(), signed, signOpts)
   708  		if err != nil {
   709  			c.sendAlert(alertInternalError)
   710  			return err
   711  		}
   712  
   713  		if _, err := hs.c.writeHandshakeRecord(certVerify, &hs.finishedHash); err != nil {
   714  			return err
   715  		}
   716  	}
   717  
   718  	hs.finishedHash.discardHandshakeBuffer()
   719  
   720  	return nil
   721  }
   722  
   723  func (hs *clientHandshakeState) establishKeys() error {
   724  	c := hs.c
   725  
   726  	clientMAC, serverMAC, clientKey, serverKey, clientIV, serverIV :=
   727  		keysFromMasterSecret(c.vers, hs.suite, hs.masterSecret, hs.hello.random, hs.serverHello.random, hs.suite.macLen, hs.suite.keyLen, hs.suite.ivLen)
   728  	var clientCipher, serverCipher any
   729  	var clientHash, serverHash hash.Hash
   730  	if hs.suite.cipher != nil {
   731  		clientCipher = hs.suite.cipher(clientKey, clientIV, false /* not for reading */)
   732  		clientHash = hs.suite.mac(clientMAC)
   733  		serverCipher = hs.suite.cipher(serverKey, serverIV, true /* for reading */)
   734  		serverHash = hs.suite.mac(serverMAC)
   735  	} else {
   736  		clientCipher = hs.suite.aead(clientKey, clientIV)
   737  		serverCipher = hs.suite.aead(serverKey, serverIV)
   738  	}
   739  
   740  	c.in.prepareCipherSpec(c.vers, serverCipher, serverHash)
   741  	c.out.prepareCipherSpec(c.vers, clientCipher, clientHash)
   742  	return nil
   743  }
   744  
   745  func (hs *clientHandshakeState) serverResumedSession() bool {
   746  	// If the server responded with the same sessionId then it means the
   747  	// sessionTicket is being used to resume a TLS session.
   748  	return hs.session != nil && hs.hello.sessionId != nil &&
   749  		bytes.Equal(hs.serverHello.sessionId, hs.hello.sessionId)
   750  }
   751  
   752  func (hs *clientHandshakeState) processServerHello() (bool, error) {
   753  	c := hs.c
   754  
   755  	if err := hs.pickCipherSuite(); err != nil {
   756  		return false, err
   757  	}
   758  
   759  	if hs.serverHello.compressionMethod != compressionNone {
   760  		c.sendAlert(alertUnexpectedMessage)
   761  		return false, errors.New("tls: server selected unsupported compression format")
   762  	}
   763  
   764  	if c.handshakes == 0 && hs.serverHello.secureRenegotiationSupported {
   765  		c.secureRenegotiation = true
   766  		if len(hs.serverHello.secureRenegotiation) != 0 {
   767  			c.sendAlert(alertHandshakeFailure)
   768  			return false, errors.New("tls: initial handshake had non-empty renegotiation extension")
   769  		}
   770  	}
   771  
   772  	if c.handshakes > 0 && c.secureRenegotiation {
   773  		var expectedSecureRenegotiation [24]byte
   774  		copy(expectedSecureRenegotiation[:], c.clientFinished[:])
   775  		copy(expectedSecureRenegotiation[12:], c.serverFinished[:])
   776  		if !bytes.Equal(hs.serverHello.secureRenegotiation, expectedSecureRenegotiation[:]) {
   777  			c.sendAlert(alertHandshakeFailure)
   778  			return false, errors.New("tls: incorrect renegotiation extension contents")
   779  		}
   780  	}
   781  
   782  	if err := checkALPN(hs.hello.alpnProtocols, hs.serverHello.alpnProtocol, false); err != nil {
   783  		c.sendAlert(alertUnsupportedExtension)
   784  		return false, err
   785  	}
   786  	c.clientProtocol = hs.serverHello.alpnProtocol
   787  
   788  	c.scts = hs.serverHello.scts
   789  
   790  	if !hs.serverResumedSession() {
   791  		return false, nil
   792  	}
   793  
   794  	if hs.session.version != c.vers {
   795  		c.sendAlert(alertHandshakeFailure)
   796  		return false, errors.New("tls: server resumed a session with a different version")
   797  	}
   798  
   799  	if hs.session.cipherSuite != hs.suite.id {
   800  		c.sendAlert(alertHandshakeFailure)
   801  		return false, errors.New("tls: server resumed a session with a different cipher suite")
   802  	}
   803  
   804  	// RFC 7627, Section 5.3
   805  	if hs.session.extMasterSecret != hs.serverHello.extendedMasterSecret {
   806  		c.sendAlert(alertHandshakeFailure)
   807  		return false, errors.New("tls: server resumed a session with a different EMS extension")
   808  	}
   809  
   810  	// Restore master secret and certificates from previous state
   811  	hs.masterSecret = hs.session.secret
   812  	c.extMasterSecret = hs.session.extMasterSecret
   813  	c.peerCertificates = hs.session.peerCertificates
   814  	c.activeCertHandles = hs.c.activeCertHandles
   815  	c.verifiedChains = hs.session.verifiedChains
   816  	c.ocspResponse = hs.session.ocspResponse
   817  	// Let the ServerHello SCTs override the session SCTs from the original
   818  	// connection, if any are provided
   819  	if len(c.scts) == 0 && len(hs.session.scts) != 0 {
   820  		c.scts = hs.session.scts
   821  	}
   822  
   823  	return true, nil
   824  }
   825  
   826  // checkALPN ensure that the server's choice of ALPN protocol is compatible with
   827  // the protocols that we advertised in the Client Hello.
   828  func checkALPN(clientProtos []string, serverProto string, quic bool) error {
   829  	if serverProto == "" {
   830  		if quic && len(clientProtos) > 0 {
   831  			// RFC 9001, Section 8.1
   832  			return errors.New("tls: server did not select an ALPN protocol")
   833  		}
   834  		return nil
   835  	}
   836  	if len(clientProtos) == 0 {
   837  		return errors.New("tls: server advertised unrequested ALPN extension")
   838  	}
   839  	for _, proto := range clientProtos {
   840  		if proto == serverProto {
   841  			return nil
   842  		}
   843  	}
   844  	return errors.New("tls: server selected unadvertised ALPN protocol")
   845  }
   846  
   847  func (hs *clientHandshakeState) readFinished(out []byte) error {
   848  	c := hs.c
   849  
   850  	if err := c.readChangeCipherSpec(); err != nil {
   851  		return err
   852  	}
   853  
   854  	// finishedMsg is included in the transcript, but not until after we
   855  	// check the client version, since the state before this message was
   856  	// sent is used during verification.
   857  	msg, err := c.readHandshake(nil)
   858  	if err != nil {
   859  		return err
   860  	}
   861  	serverFinished, ok := msg.(*finishedMsg)
   862  	if !ok {
   863  		c.sendAlert(alertUnexpectedMessage)
   864  		return unexpectedMessageError(serverFinished, msg)
   865  	}
   866  
   867  	verify := hs.finishedHash.serverSum(hs.masterSecret)
   868  	if len(verify) != len(serverFinished.verifyData) ||
   869  		subtle.ConstantTimeCompare(verify, serverFinished.verifyData) != 1 {
   870  		c.sendAlert(alertHandshakeFailure)
   871  		return errors.New("tls: server's Finished message was incorrect")
   872  	}
   873  
   874  	if err := transcriptMsg(serverFinished, &hs.finishedHash); err != nil {
   875  		return err
   876  	}
   877  
   878  	copy(out, verify)
   879  	return nil
   880  }
   881  
   882  func (hs *clientHandshakeState) readSessionTicket() error {
   883  	if !hs.serverHello.ticketSupported {
   884  		return nil
   885  	}
   886  	c := hs.c
   887  
   888  	if !hs.hello.ticketSupported {
   889  		c.sendAlert(alertIllegalParameter)
   890  		return errors.New("tls: server sent unrequested session ticket")
   891  	}
   892  
   893  	msg, err := c.readHandshake(&hs.finishedHash)
   894  	if err != nil {
   895  		return err
   896  	}
   897  	sessionTicketMsg, ok := msg.(*newSessionTicketMsg)
   898  	if !ok {
   899  		c.sendAlert(alertUnexpectedMessage)
   900  		return unexpectedMessageError(sessionTicketMsg, msg)
   901  	}
   902  
   903  	hs.ticket = sessionTicketMsg.ticket
   904  	return nil
   905  }
   906  
   907  func (hs *clientHandshakeState) saveSessionTicket() error {
   908  	if hs.ticket == nil {
   909  		return nil
   910  	}
   911  	c := hs.c
   912  
   913  	cacheKey := c.clientSessionCacheKey()
   914  	if cacheKey == "" {
   915  		return nil
   916  	}
   917  
   918  	session, err := c.sessionState()
   919  	if err != nil {
   920  		return err
   921  	}
   922  	session.secret = hs.masterSecret
   923  
   924  	cs := &ClientSessionState{ticket: hs.ticket, session: session}
   925  	c.config.ClientSessionCache.Put(cacheKey, cs)
   926  	return nil
   927  }
   928  
   929  func (hs *clientHandshakeState) sendFinished(out []byte) error {
   930  	c := hs.c
   931  
   932  	if err := c.writeChangeCipherRecord(); err != nil {
   933  		return err
   934  	}
   935  
   936  	finished := new(finishedMsg)
   937  	finished.verifyData = hs.finishedHash.clientSum(hs.masterSecret)
   938  	if _, err := hs.c.writeHandshakeRecord(finished, &hs.finishedHash); err != nil {
   939  		return err
   940  	}
   941  	copy(out, finished.verifyData)
   942  	return nil
   943  }
   944  
   945  // defaultMaxRSAKeySize is the maximum RSA key size in bits that we are willing
   946  // to verify the signatures of during a TLS handshake.
   947  const defaultMaxRSAKeySize = 8192
   948  
   949  var tlsmaxrsasize = godebug.New("tlsmaxrsasize")
   950  
   951  func checkKeySize(n int) (max int, ok bool) {
   952  	if v := tlsmaxrsasize.Value(); v != "" {
   953  		if max, err := strconv.Atoi(v); err == nil {
   954  			if (n <= max) != (n <= defaultMaxRSAKeySize) {
   955  				tlsmaxrsasize.IncNonDefault()
   956  			}
   957  			return max, n <= max
   958  		}
   959  	}
   960  	return defaultMaxRSAKeySize, n <= defaultMaxRSAKeySize
   961  }
   962  
   963  // verifyServerCertificate parses and verifies the provided chain, setting
   964  // c.verifiedChains and c.peerCertificates or sending the appropriate alert.
   965  func (c *Conn) verifyServerCertificate(certificates [][]byte) error {
   966  	activeHandles := make([]*activeCert, len(certificates))
   967  	certs := make([]*x509.Certificate, len(certificates))
   968  	for i, asn1Data := range certificates {
   969  		cert, err := globalCertCache.newCert(asn1Data)
   970  		if err != nil {
   971  			c.sendAlert(alertBadCertificate)
   972  			return errors.New("tls: failed to parse certificate from server: " + err.Error())
   973  		}
   974  		if cert.cert.PublicKeyAlgorithm == x509.RSA {
   975  			n := cert.cert.PublicKey.(*rsa.PublicKey).N.BitLen()
   976  			if max, ok := checkKeySize(n); !ok {
   977  				c.sendAlert(alertBadCertificate)
   978  				return fmt.Errorf("tls: server sent certificate containing RSA key larger than %d bits", max)
   979  			}
   980  		}
   981  		activeHandles[i] = cert
   982  		certs[i] = cert.cert
   983  	}
   984  
   985  	if !c.config.InsecureSkipVerify {
   986  		opts := x509.VerifyOptions{
   987  			Roots:         c.config.RootCAs,
   988  			CurrentTime:   c.config.time(),
   989  			DNSName:       c.config.ServerName,
   990  			Intermediates: x509.NewCertPool(),
   991  		}
   992  
   993  		for _, cert := range certs[1:] {
   994  			opts.Intermediates.AddCert(cert)
   995  		}
   996  		var err error
   997  		c.verifiedChains, err = certs[0].Verify(opts)
   998  		if err != nil {
   999  			c.sendAlert(alertBadCertificate)
  1000  			return &CertificateVerificationError{UnverifiedCertificates: certs, Err: err}
  1001  		}
  1002  	}
  1003  
  1004  	switch certs[0].PublicKey.(type) {
  1005  	case *rsa.PublicKey, *ecdsa.PublicKey, ed25519.PublicKey:
  1006  		break
  1007  	default:
  1008  		c.sendAlert(alertUnsupportedCertificate)
  1009  		return fmt.Errorf("tls: server's certificate contains an unsupported type of public key: %T", certs[0].PublicKey)
  1010  	}
  1011  
  1012  	c.activeCertHandles = activeHandles
  1013  	c.peerCertificates = certs
  1014  
  1015  	if c.config.VerifyPeerCertificate != nil {
  1016  		if err := c.config.VerifyPeerCertificate(certificates, c.verifiedChains); err != nil {
  1017  			c.sendAlert(alertBadCertificate)
  1018  			return err
  1019  		}
  1020  	}
  1021  
  1022  	if c.config.VerifyConnection != nil {
  1023  		if err := c.config.VerifyConnection(c.connectionStateLocked()); err != nil {
  1024  			c.sendAlert(alertBadCertificate)
  1025  			return err
  1026  		}
  1027  	}
  1028  
  1029  	return nil
  1030  }
  1031  
  1032  // certificateRequestInfoFromMsg generates a CertificateRequestInfo from a TLS
  1033  // <= 1.2 CertificateRequest, making an effort to fill in missing information.
  1034  func certificateRequestInfoFromMsg(ctx context.Context, vers uint16, certReq *certificateRequestMsg) *CertificateRequestInfo {
  1035  	cri := &CertificateRequestInfo{
  1036  		AcceptableCAs: certReq.certificateAuthorities,
  1037  		Version:       vers,
  1038  		ctx:           ctx,
  1039  	}
  1040  
  1041  	var rsaAvail, ecAvail bool
  1042  	for _, certType := range certReq.certificateTypes {
  1043  		switch certType {
  1044  		case certTypeRSASign:
  1045  			rsaAvail = true
  1046  		case certTypeECDSASign:
  1047  			ecAvail = true
  1048  		}
  1049  	}
  1050  
  1051  	if !certReq.hasSignatureAlgorithm {
  1052  		// Prior to TLS 1.2, signature schemes did not exist. In this case we
  1053  		// make up a list based on the acceptable certificate types, to help
  1054  		// GetClientCertificate and SupportsCertificate select the right certificate.
  1055  		// The hash part of the SignatureScheme is a lie here, because
  1056  		// TLS 1.0 and 1.1 always use MD5+SHA1 for RSA and SHA1 for ECDSA.
  1057  		switch {
  1058  		case rsaAvail && ecAvail:
  1059  			cri.SignatureSchemes = []SignatureScheme{
  1060  				ECDSAWithP256AndSHA256, ECDSAWithP384AndSHA384, ECDSAWithP521AndSHA512,
  1061  				PKCS1WithSHA256, PKCS1WithSHA384, PKCS1WithSHA512, PKCS1WithSHA1,
  1062  			}
  1063  		case rsaAvail:
  1064  			cri.SignatureSchemes = []SignatureScheme{
  1065  				PKCS1WithSHA256, PKCS1WithSHA384, PKCS1WithSHA512, PKCS1WithSHA1,
  1066  			}
  1067  		case ecAvail:
  1068  			cri.SignatureSchemes = []SignatureScheme{
  1069  				ECDSAWithP256AndSHA256, ECDSAWithP384AndSHA384, ECDSAWithP521AndSHA512,
  1070  			}
  1071  		}
  1072  		return cri
  1073  	}
  1074  
  1075  	// Filter the signature schemes based on the certificate types.
  1076  	// See RFC 5246, Section 7.4.4 (where it calls this "somewhat complicated").
  1077  	cri.SignatureSchemes = make([]SignatureScheme, 0, len(certReq.supportedSignatureAlgorithms))
  1078  	for _, sigScheme := range certReq.supportedSignatureAlgorithms {
  1079  		sigType, _, err := typeAndHashFromSignatureScheme(sigScheme)
  1080  		if err != nil {
  1081  			continue
  1082  		}
  1083  		switch sigType {
  1084  		case signatureECDSA, signatureEd25519:
  1085  			if ecAvail {
  1086  				cri.SignatureSchemes = append(cri.SignatureSchemes, sigScheme)
  1087  			}
  1088  		case signatureRSAPSS, signaturePKCS1v15:
  1089  			if rsaAvail {
  1090  				cri.SignatureSchemes = append(cri.SignatureSchemes, sigScheme)
  1091  			}
  1092  		}
  1093  	}
  1094  
  1095  	return cri
  1096  }
  1097  
  1098  func (c *Conn) getClientCertificate(cri *CertificateRequestInfo) (*Certificate, error) {
  1099  	if c.config.GetClientCertificate != nil {
  1100  		return c.config.GetClientCertificate(cri)
  1101  	}
  1102  
  1103  	for _, chain := range c.config.Certificates {
  1104  		if err := cri.SupportsCertificate(&chain); err != nil {
  1105  			continue
  1106  		}
  1107  		return &chain, nil
  1108  	}
  1109  
  1110  	// No acceptable certificate found. Don't send a certificate.
  1111  	return new(Certificate), nil
  1112  }
  1113  
  1114  // clientSessionCacheKey returns a key used to cache sessionTickets that could
  1115  // be used to resume previously negotiated TLS sessions with a server.
  1116  func (c *Conn) clientSessionCacheKey() string {
  1117  	if len(c.config.ServerName) > 0 {
  1118  		return c.config.ServerName
  1119  	}
  1120  	if c.conn != nil {
  1121  		return c.conn.RemoteAddr().String()
  1122  	}
  1123  	return ""
  1124  }
  1125  
  1126  // hostnameInSNI converts name into an appropriate hostname for SNI.
  1127  // Literal IP addresses and absolute FQDNs are not permitted as SNI values.
  1128  // See RFC 6066, Section 3.
  1129  func hostnameInSNI(name string) string {
  1130  	host := name
  1131  	if len(host) > 0 && host[0] == '[' && host[len(host)-1] == ']' {
  1132  		host = host[1 : len(host)-1]
  1133  	}
  1134  	if i := strings.LastIndex(host, "%"); i > 0 {
  1135  		host = host[:i]
  1136  	}
  1137  	if net.ParseIP(host) != nil {
  1138  		return ""
  1139  	}
  1140  	for len(name) > 0 && name[len(name)-1] == '.' {
  1141  		name = name[:len(name)-1]
  1142  	}
  1143  	return name
  1144  }
  1145  

View as plain text