...

Source file src/crypto/tls/handshake_client.go

Documentation: crypto/tls

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

View as plain text