...
Run Format

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  	"crypto"
    10  	"crypto/ecdsa"
    11  	"crypto/rsa"
    12  	"crypto/subtle"
    13  	"crypto/x509"
    14  	"errors"
    15  	"fmt"
    16  	"io"
    17  	"net"
    18  	"strconv"
    19  	"strings"
    20  	"sync/atomic"
    21  )
    22  
    23  type clientHandshakeState struct {
    24  	c            *Conn
    25  	serverHello  *serverHelloMsg
    26  	hello        *clientHelloMsg
    27  	suite        *cipherSuite
    28  	finishedHash finishedHash
    29  	masterSecret []byte
    30  	session      *ClientSessionState
    31  }
    32  
    33  func makeClientHello(config *Config) (*clientHelloMsg, error) {
    34  	if len(config.ServerName) == 0 && !config.InsecureSkipVerify {
    35  		return nil, errors.New("tls: either ServerName or InsecureSkipVerify must be specified in the tls.Config")
    36  	}
    37  
    38  	nextProtosLength := 0
    39  	for _, proto := range config.NextProtos {
    40  		if l := len(proto); l == 0 || l > 255 {
    41  			return nil, errors.New("tls: invalid NextProtos value")
    42  		} else {
    43  			nextProtosLength += 1 + l
    44  		}
    45  	}
    46  
    47  	if nextProtosLength > 0xffff {
    48  		return nil, errors.New("tls: NextProtos values too large")
    49  	}
    50  
    51  	hello := &clientHelloMsg{
    52  		vers:                         config.maxVersion(),
    53  		compressionMethods:           []uint8{compressionNone},
    54  		random:                       make([]byte, 32),
    55  		ocspStapling:                 true,
    56  		scts:                         true,
    57  		serverName:                   hostnameInSNI(config.ServerName),
    58  		supportedCurves:              config.curvePreferences(),
    59  		supportedPoints:              []uint8{pointFormatUncompressed},
    60  		nextProtoNeg:                 len(config.NextProtos) > 0,
    61  		secureRenegotiationSupported: true,
    62  		alpnProtocols:                config.NextProtos,
    63  	}
    64  	possibleCipherSuites := config.cipherSuites()
    65  	hello.cipherSuites = make([]uint16, 0, len(possibleCipherSuites))
    66  
    67  NextCipherSuite:
    68  	for _, suiteId := range possibleCipherSuites {
    69  		for _, suite := range cipherSuites {
    70  			if suite.id != suiteId {
    71  				continue
    72  			}
    73  			// Don't advertise TLS 1.2-only cipher suites unless
    74  			// we're attempting TLS 1.2.
    75  			if hello.vers < VersionTLS12 && suite.flags&suiteTLS12 != 0 {
    76  				continue
    77  			}
    78  			hello.cipherSuites = append(hello.cipherSuites, suiteId)
    79  			continue NextCipherSuite
    80  		}
    81  	}
    82  
    83  	_, err := io.ReadFull(config.rand(), hello.random)
    84  	if err != nil {
    85  		return nil, errors.New("tls: short read from Rand: " + err.Error())
    86  	}
    87  
    88  	if hello.vers >= VersionTLS12 {
    89  		hello.supportedSignatureAlgorithms = supportedSignatureAlgorithms
    90  	}
    91  
    92  	return hello, nil
    93  }
    94  
    95  func (c *Conn) clientHandshake() error {
    96  	if c.config == nil {
    97  		c.config = defaultConfig()
    98  	}
    99  
   100  	// This may be a renegotiation handshake, in which case some fields
   101  	// need to be reset.
   102  	c.didResume = false
   103  
   104  	hello, err := makeClientHello(c.config)
   105  	if err != nil {
   106  		return err
   107  	}
   108  
   109  	if c.handshakes > 0 {
   110  		hello.secureRenegotiation = c.clientFinished[:]
   111  	}
   112  
   113  	var session *ClientSessionState
   114  	var cacheKey string
   115  	sessionCache := c.config.ClientSessionCache
   116  	if c.config.SessionTicketsDisabled {
   117  		sessionCache = nil
   118  	}
   119  
   120  	if sessionCache != nil {
   121  		hello.ticketSupported = true
   122  	}
   123  
   124  	// Session resumption is not allowed if renegotiating because
   125  	// renegotiation is primarily used to allow a client to send a client
   126  	// certificate, which would be skipped if session resumption occurred.
   127  	if sessionCache != nil && c.handshakes == 0 {
   128  		// Try to resume a previously negotiated TLS session, if
   129  		// available.
   130  		cacheKey = clientSessionCacheKey(c.conn.RemoteAddr(), c.config)
   131  		candidateSession, ok := sessionCache.Get(cacheKey)
   132  		if ok {
   133  			// Check that the ciphersuite/version used for the
   134  			// previous session are still valid.
   135  			cipherSuiteOk := false
   136  			for _, id := range hello.cipherSuites {
   137  				if id == candidateSession.cipherSuite {
   138  					cipherSuiteOk = true
   139  					break
   140  				}
   141  			}
   142  
   143  			versOk := candidateSession.vers >= c.config.minVersion() &&
   144  				candidateSession.vers <= c.config.maxVersion()
   145  			if versOk && cipherSuiteOk {
   146  				session = candidateSession
   147  			}
   148  		}
   149  	}
   150  
   151  	if session != nil {
   152  		hello.sessionTicket = session.sessionTicket
   153  		// A random session ID is used to detect when the
   154  		// server accepted the ticket and is resuming a session
   155  		// (see RFC 5077).
   156  		hello.sessionId = make([]byte, 16)
   157  		if _, err := io.ReadFull(c.config.rand(), hello.sessionId); err != nil {
   158  			return errors.New("tls: short read from Rand: " + err.Error())
   159  		}
   160  	}
   161  
   162  	hs := &clientHandshakeState{
   163  		c:       c,
   164  		hello:   hello,
   165  		session: session,
   166  	}
   167  
   168  	if err = hs.handshake(); err != nil {
   169  		return err
   170  	}
   171  
   172  	// If we had a successful handshake and hs.session is different from
   173  	// the one already cached - cache a new one
   174  	if sessionCache != nil && hs.session != nil && session != hs.session {
   175  		sessionCache.Put(cacheKey, hs.session)
   176  	}
   177  
   178  	return nil
   179  }
   180  
   181  // Does the handshake, either a full one or resumes old session.
   182  // Requires hs.c, hs.hello, and, optionally, hs.session to be set.
   183  func (hs *clientHandshakeState) handshake() error {
   184  	c := hs.c
   185  
   186  	// send ClientHello
   187  	if _, err := c.writeRecord(recordTypeHandshake, hs.hello.marshal()); err != nil {
   188  		return err
   189  	}
   190  
   191  	msg, err := c.readHandshake()
   192  	if err != nil {
   193  		return err
   194  	}
   195  
   196  	var ok bool
   197  	if hs.serverHello, ok = msg.(*serverHelloMsg); !ok {
   198  		c.sendAlert(alertUnexpectedMessage)
   199  		return unexpectedMessageError(hs.serverHello, msg)
   200  	}
   201  
   202  	if err = hs.pickTLSVersion(); err != nil {
   203  		return err
   204  	}
   205  
   206  	if err = hs.pickCipherSuite(); err != nil {
   207  		return err
   208  	}
   209  
   210  	isResume, err := hs.processServerHello()
   211  	if err != nil {
   212  		return err
   213  	}
   214  
   215  	hs.finishedHash = newFinishedHash(c.vers, hs.suite)
   216  
   217  	// No signatures of the handshake are needed in a resumption.
   218  	// Otherwise, in a full handshake, if we don't have any certificates
   219  	// configured then we will never send a CertificateVerify message and
   220  	// thus no signatures are needed in that case either.
   221  	if isResume || (len(c.config.Certificates) == 0 && c.config.GetClientCertificate == nil) {
   222  		hs.finishedHash.discardHandshakeBuffer()
   223  	}
   224  
   225  	hs.finishedHash.Write(hs.hello.marshal())
   226  	hs.finishedHash.Write(hs.serverHello.marshal())
   227  
   228  	c.buffering = true
   229  	if isResume {
   230  		if err := hs.establishKeys(); err != nil {
   231  			return err
   232  		}
   233  		if err := hs.readSessionTicket(); err != nil {
   234  			return err
   235  		}
   236  		if err := hs.readFinished(c.serverFinished[:]); err != nil {
   237  			return err
   238  		}
   239  		c.clientFinishedIsFirst = false
   240  		if err := hs.sendFinished(c.clientFinished[:]); err != nil {
   241  			return err
   242  		}
   243  		if _, err := c.flush(); err != nil {
   244  			return err
   245  		}
   246  	} else {
   247  		if err := hs.doFullHandshake(); err != nil {
   248  			return err
   249  		}
   250  		if err := hs.establishKeys(); err != nil {
   251  			return err
   252  		}
   253  		if err := hs.sendFinished(c.clientFinished[:]); err != nil {
   254  			return err
   255  		}
   256  		if _, err := c.flush(); err != nil {
   257  			return err
   258  		}
   259  		c.clientFinishedIsFirst = true
   260  		if err := hs.readSessionTicket(); err != nil {
   261  			return err
   262  		}
   263  		if err := hs.readFinished(c.serverFinished[:]); err != nil {
   264  			return err
   265  		}
   266  	}
   267  
   268  	c.ekm = ekmFromMasterSecret(c.vers, hs.suite, hs.masterSecret, hs.hello.random, hs.serverHello.random)
   269  	c.didResume = isResume
   270  	atomic.StoreUint32(&c.handshakeStatus, 1)
   271  
   272  	return nil
   273  }
   274  
   275  func (hs *clientHandshakeState) pickTLSVersion() error {
   276  	vers, ok := hs.c.config.mutualVersion(hs.serverHello.vers)
   277  	if !ok || vers < VersionTLS10 {
   278  		// TLS 1.0 is the minimum version supported as a client.
   279  		hs.c.sendAlert(alertProtocolVersion)
   280  		return fmt.Errorf("tls: server selected unsupported protocol version %x", hs.serverHello.vers)
   281  	}
   282  
   283  	hs.c.vers = vers
   284  	hs.c.haveVers = true
   285  
   286  	return nil
   287  }
   288  
   289  func (hs *clientHandshakeState) pickCipherSuite() error {
   290  	if hs.suite = mutualCipherSuite(hs.hello.cipherSuites, hs.serverHello.cipherSuite); hs.suite == nil {
   291  		hs.c.sendAlert(alertHandshakeFailure)
   292  		return errors.New("tls: server chose an unconfigured cipher suite")
   293  	}
   294  
   295  	hs.c.cipherSuite = hs.suite.id
   296  	return nil
   297  }
   298  
   299  func (hs *clientHandshakeState) doFullHandshake() error {
   300  	c := hs.c
   301  
   302  	msg, err := c.readHandshake()
   303  	if err != nil {
   304  		return err
   305  	}
   306  	certMsg, ok := msg.(*certificateMsg)
   307  	if !ok || len(certMsg.certificates) == 0 {
   308  		c.sendAlert(alertUnexpectedMessage)
   309  		return unexpectedMessageError(certMsg, msg)
   310  	}
   311  	hs.finishedHash.Write(certMsg.marshal())
   312  
   313  	if c.handshakes == 0 {
   314  		// If this is the first handshake on a connection, process and
   315  		// (optionally) verify the server's certificates.
   316  		certs := make([]*x509.Certificate, len(certMsg.certificates))
   317  		for i, asn1Data := range certMsg.certificates {
   318  			cert, err := x509.ParseCertificate(asn1Data)
   319  			if err != nil {
   320  				c.sendAlert(alertBadCertificate)
   321  				return errors.New("tls: failed to parse certificate from server: " + err.Error())
   322  			}
   323  			certs[i] = cert
   324  		}
   325  
   326  		if !c.config.InsecureSkipVerify {
   327  			opts := x509.VerifyOptions{
   328  				Roots:         c.config.RootCAs,
   329  				CurrentTime:   c.config.time(),
   330  				DNSName:       c.config.ServerName,
   331  				Intermediates: x509.NewCertPool(),
   332  			}
   333  
   334  			for i, cert := range certs {
   335  				if i == 0 {
   336  					continue
   337  				}
   338  				opts.Intermediates.AddCert(cert)
   339  			}
   340  			c.verifiedChains, err = certs[0].Verify(opts)
   341  			if err != nil {
   342  				c.sendAlert(alertBadCertificate)
   343  				return err
   344  			}
   345  		}
   346  
   347  		if c.config.VerifyPeerCertificate != nil {
   348  			if err := c.config.VerifyPeerCertificate(certMsg.certificates, c.verifiedChains); err != nil {
   349  				c.sendAlert(alertBadCertificate)
   350  				return err
   351  			}
   352  		}
   353  
   354  		switch certs[0].PublicKey.(type) {
   355  		case *rsa.PublicKey, *ecdsa.PublicKey:
   356  			break
   357  		default:
   358  			c.sendAlert(alertUnsupportedCertificate)
   359  			return fmt.Errorf("tls: server's certificate contains an unsupported type of public key: %T", certs[0].PublicKey)
   360  		}
   361  
   362  		c.peerCertificates = certs
   363  	} else {
   364  		// This is a renegotiation handshake. We require that the
   365  		// server's identity (i.e. leaf certificate) is unchanged and
   366  		// thus any previous trust decision is still valid.
   367  		//
   368  		// See https://mitls.org/pages/attacks/3SHAKE for the
   369  		// motivation behind this requirement.
   370  		if !bytes.Equal(c.peerCertificates[0].Raw, certMsg.certificates[0]) {
   371  			c.sendAlert(alertBadCertificate)
   372  			return errors.New("tls: server's identity changed during renegotiation")
   373  		}
   374  	}
   375  
   376  	msg, err = c.readHandshake()
   377  	if err != nil {
   378  		return err
   379  	}
   380  
   381  	cs, ok := msg.(*certificateStatusMsg)
   382  	if ok {
   383  		// RFC4366 on Certificate Status Request:
   384  		// The server MAY return a "certificate_status" message.
   385  
   386  		if !hs.serverHello.ocspStapling {
   387  			// If a server returns a "CertificateStatus" message, then the
   388  			// server MUST have included an extension of type "status_request"
   389  			// with empty "extension_data" in the extended server hello.
   390  
   391  			c.sendAlert(alertUnexpectedMessage)
   392  			return errors.New("tls: received unexpected CertificateStatus message")
   393  		}
   394  		hs.finishedHash.Write(cs.marshal())
   395  
   396  		if cs.statusType == statusTypeOCSP {
   397  			c.ocspResponse = cs.response
   398  		}
   399  
   400  		msg, err = c.readHandshake()
   401  		if err != nil {
   402  			return err
   403  		}
   404  	}
   405  
   406  	keyAgreement := hs.suite.ka(c.vers)
   407  
   408  	skx, ok := msg.(*serverKeyExchangeMsg)
   409  	if ok {
   410  		hs.finishedHash.Write(skx.marshal())
   411  		err = keyAgreement.processServerKeyExchange(c.config, hs.hello, hs.serverHello, c.peerCertificates[0], skx)
   412  		if err != nil {
   413  			c.sendAlert(alertUnexpectedMessage)
   414  			return err
   415  		}
   416  
   417  		msg, err = c.readHandshake()
   418  		if err != nil {
   419  			return err
   420  		}
   421  	}
   422  
   423  	var chainToSend *Certificate
   424  	var certRequested bool
   425  	certReq, ok := msg.(*certificateRequestMsg)
   426  	if ok {
   427  		certRequested = true
   428  		hs.finishedHash.Write(certReq.marshal())
   429  
   430  		if chainToSend, err = hs.getCertificate(certReq); err != nil {
   431  			c.sendAlert(alertInternalError)
   432  			return err
   433  		}
   434  
   435  		msg, err = c.readHandshake()
   436  		if err != nil {
   437  			return err
   438  		}
   439  	}
   440  
   441  	shd, ok := msg.(*serverHelloDoneMsg)
   442  	if !ok {
   443  		c.sendAlert(alertUnexpectedMessage)
   444  		return unexpectedMessageError(shd, msg)
   445  	}
   446  	hs.finishedHash.Write(shd.marshal())
   447  
   448  	// If the server requested a certificate then we have to send a
   449  	// Certificate message, even if it's empty because we don't have a
   450  	// certificate to send.
   451  	if certRequested {
   452  		certMsg = new(certificateMsg)
   453  		certMsg.certificates = chainToSend.Certificate
   454  		hs.finishedHash.Write(certMsg.marshal())
   455  		if _, err := c.writeRecord(recordTypeHandshake, certMsg.marshal()); err != nil {
   456  			return err
   457  		}
   458  	}
   459  
   460  	preMasterSecret, ckx, err := keyAgreement.generateClientKeyExchange(c.config, hs.hello, c.peerCertificates[0])
   461  	if err != nil {
   462  		c.sendAlert(alertInternalError)
   463  		return err
   464  	}
   465  	if ckx != nil {
   466  		hs.finishedHash.Write(ckx.marshal())
   467  		if _, err := c.writeRecord(recordTypeHandshake, ckx.marshal()); err != nil {
   468  			return err
   469  		}
   470  	}
   471  
   472  	if chainToSend != nil && len(chainToSend.Certificate) > 0 {
   473  		certVerify := &certificateVerifyMsg{
   474  			hasSignatureAndHash: c.vers >= VersionTLS12,
   475  		}
   476  
   477  		key, ok := chainToSend.PrivateKey.(crypto.Signer)
   478  		if !ok {
   479  			c.sendAlert(alertInternalError)
   480  			return fmt.Errorf("tls: client certificate private key of type %T does not implement crypto.Signer", chainToSend.PrivateKey)
   481  		}
   482  
   483  		signatureAlgorithm, sigType, hashFunc, err := pickSignatureAlgorithm(key.Public(), certReq.supportedSignatureAlgorithms, hs.hello.supportedSignatureAlgorithms, c.vers)
   484  		if err != nil {
   485  			c.sendAlert(alertInternalError)
   486  			return err
   487  		}
   488  		// SignatureAndHashAlgorithm was introduced in TLS 1.2.
   489  		if certVerify.hasSignatureAndHash {
   490  			certVerify.signatureAlgorithm = signatureAlgorithm
   491  		}
   492  		digest, err := hs.finishedHash.hashForClientCertificate(sigType, hashFunc, hs.masterSecret)
   493  		if err != nil {
   494  			c.sendAlert(alertInternalError)
   495  			return err
   496  		}
   497  		signOpts := crypto.SignerOpts(hashFunc)
   498  		if sigType == signatureRSAPSS {
   499  			signOpts = &rsa.PSSOptions{SaltLength: rsa.PSSSaltLengthEqualsHash, Hash: hashFunc}
   500  		}
   501  		certVerify.signature, err = key.Sign(c.config.rand(), digest, signOpts)
   502  		if err != nil {
   503  			c.sendAlert(alertInternalError)
   504  			return err
   505  		}
   506  
   507  		hs.finishedHash.Write(certVerify.marshal())
   508  		if _, err := c.writeRecord(recordTypeHandshake, certVerify.marshal()); err != nil {
   509  			return err
   510  		}
   511  	}
   512  
   513  	hs.masterSecret = masterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret, hs.hello.random, hs.serverHello.random)
   514  	if err := c.config.writeKeyLog(hs.hello.random, hs.masterSecret); err != nil {
   515  		c.sendAlert(alertInternalError)
   516  		return errors.New("tls: failed to write to key log: " + err.Error())
   517  	}
   518  
   519  	hs.finishedHash.discardHandshakeBuffer()
   520  
   521  	return nil
   522  }
   523  
   524  func (hs *clientHandshakeState) establishKeys() error {
   525  	c := hs.c
   526  
   527  	clientMAC, serverMAC, clientKey, serverKey, clientIV, serverIV :=
   528  		keysFromMasterSecret(c.vers, hs.suite, hs.masterSecret, hs.hello.random, hs.serverHello.random, hs.suite.macLen, hs.suite.keyLen, hs.suite.ivLen)
   529  	var clientCipher, serverCipher interface{}
   530  	var clientHash, serverHash macFunction
   531  	if hs.suite.cipher != nil {
   532  		clientCipher = hs.suite.cipher(clientKey, clientIV, false /* not for reading */)
   533  		clientHash = hs.suite.mac(c.vers, clientMAC)
   534  		serverCipher = hs.suite.cipher(serverKey, serverIV, true /* for reading */)
   535  		serverHash = hs.suite.mac(c.vers, serverMAC)
   536  	} else {
   537  		clientCipher = hs.suite.aead(clientKey, clientIV)
   538  		serverCipher = hs.suite.aead(serverKey, serverIV)
   539  	}
   540  
   541  	c.in.prepareCipherSpec(c.vers, serverCipher, serverHash)
   542  	c.out.prepareCipherSpec(c.vers, clientCipher, clientHash)
   543  	return nil
   544  }
   545  
   546  func (hs *clientHandshakeState) serverResumedSession() bool {
   547  	// If the server responded with the same sessionId then it means the
   548  	// sessionTicket is being used to resume a TLS session.
   549  	return hs.session != nil && hs.hello.sessionId != nil &&
   550  		bytes.Equal(hs.serverHello.sessionId, hs.hello.sessionId)
   551  }
   552  
   553  func (hs *clientHandshakeState) processServerHello() (bool, error) {
   554  	c := hs.c
   555  
   556  	if hs.serverHello.compressionMethod != compressionNone {
   557  		c.sendAlert(alertUnexpectedMessage)
   558  		return false, errors.New("tls: server selected unsupported compression format")
   559  	}
   560  
   561  	if c.handshakes == 0 && hs.serverHello.secureRenegotiationSupported {
   562  		c.secureRenegotiation = true
   563  		if len(hs.serverHello.secureRenegotiation) != 0 {
   564  			c.sendAlert(alertHandshakeFailure)
   565  			return false, errors.New("tls: initial handshake had non-empty renegotiation extension")
   566  		}
   567  	}
   568  
   569  	if c.handshakes > 0 && c.secureRenegotiation {
   570  		var expectedSecureRenegotiation [24]byte
   571  		copy(expectedSecureRenegotiation[:], c.clientFinished[:])
   572  		copy(expectedSecureRenegotiation[12:], c.serverFinished[:])
   573  		if !bytes.Equal(hs.serverHello.secureRenegotiation, expectedSecureRenegotiation[:]) {
   574  			c.sendAlert(alertHandshakeFailure)
   575  			return false, errors.New("tls: incorrect renegotiation extension contents")
   576  		}
   577  	}
   578  
   579  	clientDidNPN := hs.hello.nextProtoNeg
   580  	clientDidALPN := len(hs.hello.alpnProtocols) > 0
   581  	serverHasNPN := hs.serverHello.nextProtoNeg
   582  	serverHasALPN := len(hs.serverHello.alpnProtocol) > 0
   583  
   584  	if !clientDidNPN && serverHasNPN {
   585  		c.sendAlert(alertHandshakeFailure)
   586  		return false, errors.New("tls: server advertised unrequested NPN extension")
   587  	}
   588  
   589  	if !clientDidALPN && serverHasALPN {
   590  		c.sendAlert(alertHandshakeFailure)
   591  		return false, errors.New("tls: server advertised unrequested ALPN extension")
   592  	}
   593  
   594  	if serverHasNPN && serverHasALPN {
   595  		c.sendAlert(alertHandshakeFailure)
   596  		return false, errors.New("tls: server advertised both NPN and ALPN extensions")
   597  	}
   598  
   599  	if serverHasALPN {
   600  		c.clientProtocol = hs.serverHello.alpnProtocol
   601  		c.clientProtocolFallback = false
   602  	}
   603  	c.scts = hs.serverHello.scts
   604  
   605  	if !hs.serverResumedSession() {
   606  		return false, nil
   607  	}
   608  
   609  	if hs.session.vers != c.vers {
   610  		c.sendAlert(alertHandshakeFailure)
   611  		return false, errors.New("tls: server resumed a session with a different version")
   612  	}
   613  
   614  	if hs.session.cipherSuite != hs.suite.id {
   615  		c.sendAlert(alertHandshakeFailure)
   616  		return false, errors.New("tls: server resumed a session with a different cipher suite")
   617  	}
   618  
   619  	// Restore masterSecret and peerCerts from previous state
   620  	hs.masterSecret = hs.session.masterSecret
   621  	c.peerCertificates = hs.session.serverCertificates
   622  	c.verifiedChains = hs.session.verifiedChains
   623  	return true, nil
   624  }
   625  
   626  func (hs *clientHandshakeState) readFinished(out []byte) error {
   627  	c := hs.c
   628  
   629  	c.readRecord(recordTypeChangeCipherSpec)
   630  	if c.in.err != nil {
   631  		return c.in.err
   632  	}
   633  
   634  	msg, err := c.readHandshake()
   635  	if err != nil {
   636  		return err
   637  	}
   638  	serverFinished, ok := msg.(*finishedMsg)
   639  	if !ok {
   640  		c.sendAlert(alertUnexpectedMessage)
   641  		return unexpectedMessageError(serverFinished, msg)
   642  	}
   643  
   644  	verify := hs.finishedHash.serverSum(hs.masterSecret)
   645  	if len(verify) != len(serverFinished.verifyData) ||
   646  		subtle.ConstantTimeCompare(verify, serverFinished.verifyData) != 1 {
   647  		c.sendAlert(alertHandshakeFailure)
   648  		return errors.New("tls: server's Finished message was incorrect")
   649  	}
   650  	hs.finishedHash.Write(serverFinished.marshal())
   651  	copy(out, verify)
   652  	return nil
   653  }
   654  
   655  func (hs *clientHandshakeState) readSessionTicket() error {
   656  	if !hs.serverHello.ticketSupported {
   657  		return nil
   658  	}
   659  
   660  	c := hs.c
   661  	msg, err := c.readHandshake()
   662  	if err != nil {
   663  		return err
   664  	}
   665  	sessionTicketMsg, ok := msg.(*newSessionTicketMsg)
   666  	if !ok {
   667  		c.sendAlert(alertUnexpectedMessage)
   668  		return unexpectedMessageError(sessionTicketMsg, msg)
   669  	}
   670  	hs.finishedHash.Write(sessionTicketMsg.marshal())
   671  
   672  	hs.session = &ClientSessionState{
   673  		sessionTicket:      sessionTicketMsg.ticket,
   674  		vers:               c.vers,
   675  		cipherSuite:        hs.suite.id,
   676  		masterSecret:       hs.masterSecret,
   677  		serverCertificates: c.peerCertificates,
   678  		verifiedChains:     c.verifiedChains,
   679  	}
   680  
   681  	return nil
   682  }
   683  
   684  func (hs *clientHandshakeState) sendFinished(out []byte) error {
   685  	c := hs.c
   686  
   687  	if _, err := c.writeRecord(recordTypeChangeCipherSpec, []byte{1}); err != nil {
   688  		return err
   689  	}
   690  	if hs.serverHello.nextProtoNeg {
   691  		nextProto := new(nextProtoMsg)
   692  		proto, fallback := mutualProtocol(c.config.NextProtos, hs.serverHello.nextProtos)
   693  		nextProto.proto = proto
   694  		c.clientProtocol = proto
   695  		c.clientProtocolFallback = fallback
   696  
   697  		hs.finishedHash.Write(nextProto.marshal())
   698  		if _, err := c.writeRecord(recordTypeHandshake, nextProto.marshal()); err != nil {
   699  			return err
   700  		}
   701  	}
   702  
   703  	finished := new(finishedMsg)
   704  	finished.verifyData = hs.finishedHash.clientSum(hs.masterSecret)
   705  	hs.finishedHash.Write(finished.marshal())
   706  	if _, err := c.writeRecord(recordTypeHandshake, finished.marshal()); err != nil {
   707  		return err
   708  	}
   709  	copy(out, finished.verifyData)
   710  	return nil
   711  }
   712  
   713  // tls11SignatureSchemes contains the signature schemes that we synthesise for
   714  // a TLS <= 1.1 connection, based on the supported certificate types.
   715  var tls11SignatureSchemes = []SignatureScheme{ECDSAWithP256AndSHA256, ECDSAWithP384AndSHA384, ECDSAWithP521AndSHA512, PKCS1WithSHA256, PKCS1WithSHA384, PKCS1WithSHA512, PKCS1WithSHA1}
   716  
   717  const (
   718  	// tls11SignatureSchemesNumECDSA is the number of initial elements of
   719  	// tls11SignatureSchemes that use ECDSA.
   720  	tls11SignatureSchemesNumECDSA = 3
   721  	// tls11SignatureSchemesNumRSA is the number of trailing elements of
   722  	// tls11SignatureSchemes that use RSA.
   723  	tls11SignatureSchemesNumRSA = 4
   724  )
   725  
   726  func (hs *clientHandshakeState) getCertificate(certReq *certificateRequestMsg) (*Certificate, error) {
   727  	c := hs.c
   728  
   729  	var rsaAvail, ecdsaAvail bool
   730  	for _, certType := range certReq.certificateTypes {
   731  		switch certType {
   732  		case certTypeRSASign:
   733  			rsaAvail = true
   734  		case certTypeECDSASign:
   735  			ecdsaAvail = true
   736  		}
   737  	}
   738  
   739  	if c.config.GetClientCertificate != nil {
   740  		var signatureSchemes []SignatureScheme
   741  
   742  		if !certReq.hasSignatureAndHash {
   743  			// Prior to TLS 1.2, the signature schemes were not
   744  			// included in the certificate request message. In this
   745  			// case we use a plausible list based on the acceptable
   746  			// certificate types.
   747  			signatureSchemes = tls11SignatureSchemes
   748  			if !ecdsaAvail {
   749  				signatureSchemes = signatureSchemes[tls11SignatureSchemesNumECDSA:]
   750  			}
   751  			if !rsaAvail {
   752  				signatureSchemes = signatureSchemes[:len(signatureSchemes)-tls11SignatureSchemesNumRSA]
   753  			}
   754  		} else {
   755  			signatureSchemes = certReq.supportedSignatureAlgorithms
   756  		}
   757  
   758  		return c.config.GetClientCertificate(&CertificateRequestInfo{
   759  			AcceptableCAs:    certReq.certificateAuthorities,
   760  			SignatureSchemes: signatureSchemes,
   761  		})
   762  	}
   763  
   764  	// RFC 4346 on the certificateAuthorities field: A list of the
   765  	// distinguished names of acceptable certificate authorities.
   766  	// These distinguished names may specify a desired
   767  	// distinguished name for a root CA or for a subordinate CA;
   768  	// thus, this message can be used to describe both known roots
   769  	// and a desired authorization space. If the
   770  	// certificate_authorities list is empty then the client MAY
   771  	// send any certificate of the appropriate
   772  	// ClientCertificateType, unless there is some external
   773  	// arrangement to the contrary.
   774  
   775  	// We need to search our list of client certs for one
   776  	// where SignatureAlgorithm is acceptable to the server and the
   777  	// Issuer is in certReq.certificateAuthorities
   778  findCert:
   779  	for i, chain := range c.config.Certificates {
   780  		if !rsaAvail && !ecdsaAvail {
   781  			continue
   782  		}
   783  
   784  		for j, cert := range chain.Certificate {
   785  			x509Cert := chain.Leaf
   786  			// parse the certificate if this isn't the leaf
   787  			// node, or if chain.Leaf was nil
   788  			if j != 0 || x509Cert == nil {
   789  				var err error
   790  				if x509Cert, err = x509.ParseCertificate(cert); err != nil {
   791  					c.sendAlert(alertInternalError)
   792  					return nil, errors.New("tls: failed to parse client certificate #" + strconv.Itoa(i) + ": " + err.Error())
   793  				}
   794  			}
   795  
   796  			switch {
   797  			case rsaAvail && x509Cert.PublicKeyAlgorithm == x509.RSA:
   798  			case ecdsaAvail && x509Cert.PublicKeyAlgorithm == x509.ECDSA:
   799  			default:
   800  				continue findCert
   801  			}
   802  
   803  			if len(certReq.certificateAuthorities) == 0 {
   804  				// they gave us an empty list, so just take the
   805  				// first cert from c.config.Certificates
   806  				return &chain, nil
   807  			}
   808  
   809  			for _, ca := range certReq.certificateAuthorities {
   810  				if bytes.Equal(x509Cert.RawIssuer, ca) {
   811  					return &chain, nil
   812  				}
   813  			}
   814  		}
   815  	}
   816  
   817  	// No acceptable certificate found. Don't send a certificate.
   818  	return new(Certificate), nil
   819  }
   820  
   821  // clientSessionCacheKey returns a key used to cache sessionTickets that could
   822  // be used to resume previously negotiated TLS sessions with a server.
   823  func clientSessionCacheKey(serverAddr net.Addr, config *Config) string {
   824  	if len(config.ServerName) > 0 {
   825  		return config.ServerName
   826  	}
   827  	return serverAddr.String()
   828  }
   829  
   830  // mutualProtocol finds the mutual Next Protocol Negotiation or ALPN protocol
   831  // given list of possible protocols and a list of the preference order. The
   832  // first list must not be empty. It returns the resulting protocol and flag
   833  // indicating if the fallback case was reached.
   834  func mutualProtocol(protos, preferenceProtos []string) (string, bool) {
   835  	for _, s := range preferenceProtos {
   836  		for _, c := range protos {
   837  			if s == c {
   838  				return s, false
   839  			}
   840  		}
   841  	}
   842  
   843  	return protos[0], true
   844  }
   845  
   846  // hostnameInSNI converts name into an approriate hostname for SNI.
   847  // Literal IP addresses and absolute FQDNs are not permitted as SNI values.
   848  // See https://tools.ietf.org/html/rfc6066#section-3.
   849  func hostnameInSNI(name string) string {
   850  	host := name
   851  	if len(host) > 0 && host[0] == '[' && host[len(host)-1] == ']' {
   852  		host = host[1 : len(host)-1]
   853  	}
   854  	if i := strings.LastIndex(host, "%"); i > 0 {
   855  		host = host[:i]
   856  	}
   857  	if net.ParseIP(host) != nil {
   858  		return ""
   859  	}
   860  	for len(name) > 0 && name[len(name)-1] == '.' {
   861  		name = name[:len(name)-1]
   862  	}
   863  	return name
   864  }
   865  

View as plain text