Black Lives Matter. Support the Equal Justice Initiative.

Source file src/crypto/tls/handshake_server.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  	"crypto"
     9  	"crypto/ecdsa"
    10  	"crypto/ed25519"
    11  	"crypto/rsa"
    12  	"crypto/subtle"
    13  	"crypto/x509"
    14  	"errors"
    15  	"fmt"
    16  	"io"
    17  	"sync/atomic"
    18  	"time"
    19  )
    20  
    21  // serverHandshakeState contains details of a server handshake in progress.
    22  // It's discarded once the handshake has completed.
    23  type serverHandshakeState struct {
    24  	c            *Conn
    25  	clientHello  *clientHelloMsg
    26  	hello        *serverHelloMsg
    27  	suite        *cipherSuite
    28  	ecdheOk      bool
    29  	ecSignOk     bool
    30  	rsaDecryptOk bool
    31  	rsaSignOk    bool
    32  	sessionState *sessionState
    33  	finishedHash finishedHash
    34  	masterSecret []byte
    35  	cert         *Certificate
    36  }
    37  
    38  // serverHandshake performs a TLS handshake as a server.
    39  func (c *Conn) serverHandshake() error {
    40  	clientHello, err := c.readClientHello()
    41  	if err != nil {
    42  		return err
    43  	}
    44  
    45  	if c.vers == VersionTLS13 {
    46  		hs := serverHandshakeStateTLS13{
    47  			c:           c,
    48  			clientHello: clientHello,
    49  		}
    50  		return hs.handshake()
    51  	}
    52  
    53  	hs := serverHandshakeState{
    54  		c:           c,
    55  		clientHello: clientHello,
    56  	}
    57  	return hs.handshake()
    58  }
    59  
    60  func (hs *serverHandshakeState) handshake() error {
    61  	c := hs.c
    62  
    63  	if err := hs.processClientHello(); err != nil {
    64  		return err
    65  	}
    66  
    67  	// For an overview of TLS handshaking, see RFC 5246, Section 7.3.
    68  	c.buffering = true
    69  	if hs.checkForResumption() {
    70  		// The client has included a session ticket and so we do an abbreviated handshake.
    71  		c.didResume = true
    72  		if err := hs.doResumeHandshake(); err != nil {
    73  			return err
    74  		}
    75  		if err := hs.establishKeys(); err != nil {
    76  			return err
    77  		}
    78  		if err := hs.sendSessionTicket(); err != nil {
    79  			return err
    80  		}
    81  		if err := hs.sendFinished(c.serverFinished[:]); err != nil {
    82  			return err
    83  		}
    84  		if _, err := c.flush(); err != nil {
    85  			return err
    86  		}
    87  		c.clientFinishedIsFirst = false
    88  		if err := hs.readFinished(nil); err != nil {
    89  			return err
    90  		}
    91  	} else {
    92  		// The client didn't include a session ticket, or it wasn't
    93  		// valid so we do a full handshake.
    94  		if err := hs.pickCipherSuite(); err != nil {
    95  			return err
    96  		}
    97  		if err := hs.doFullHandshake(); err != nil {
    98  			return err
    99  		}
   100  		if err := hs.establishKeys(); err != nil {
   101  			return err
   102  		}
   103  		if err := hs.readFinished(c.clientFinished[:]); err != nil {
   104  			return err
   105  		}
   106  		c.clientFinishedIsFirst = true
   107  		c.buffering = true
   108  		if err := hs.sendSessionTicket(); err != nil {
   109  			return err
   110  		}
   111  		if err := hs.sendFinished(nil); err != nil {
   112  			return err
   113  		}
   114  		if _, err := c.flush(); err != nil {
   115  			return err
   116  		}
   117  	}
   118  
   119  	c.ekm = ekmFromMasterSecret(c.vers, hs.suite, hs.masterSecret, hs.clientHello.random, hs.hello.random)
   120  	atomic.StoreUint32(&c.handshakeStatus, 1)
   121  
   122  	return nil
   123  }
   124  
   125  // readClientHello reads a ClientHello message and selects the protocol version.
   126  func (c *Conn) readClientHello() (*clientHelloMsg, error) {
   127  	msg, err := c.readHandshake()
   128  	if err != nil {
   129  		return nil, err
   130  	}
   131  	clientHello, ok := msg.(*clientHelloMsg)
   132  	if !ok {
   133  		c.sendAlert(alertUnexpectedMessage)
   134  		return nil, unexpectedMessageError(clientHello, msg)
   135  	}
   136  
   137  	var configForClient *Config
   138  	originalConfig := c.config
   139  	if c.config.GetConfigForClient != nil {
   140  		chi := clientHelloInfo(c, clientHello)
   141  		if configForClient, err = c.config.GetConfigForClient(chi); err != nil {
   142  			c.sendAlert(alertInternalError)
   143  			return nil, err
   144  		} else if configForClient != nil {
   145  			c.config = configForClient
   146  		}
   147  	}
   148  	c.ticketKeys = originalConfig.ticketKeys(configForClient)
   149  
   150  	clientVersions := clientHello.supportedVersions
   151  	if len(clientHello.supportedVersions) == 0 {
   152  		clientVersions = supportedVersionsFromMax(clientHello.vers)
   153  	}
   154  	c.vers, ok = c.config.mutualVersion(clientVersions)
   155  	if !ok {
   156  		c.sendAlert(alertProtocolVersion)
   157  		return nil, fmt.Errorf("tls: client offered only unsupported versions: %x", clientVersions)
   158  	}
   159  	c.haveVers = true
   160  	c.in.version = c.vers
   161  	c.out.version = c.vers
   162  
   163  	return clientHello, nil
   164  }
   165  
   166  func (hs *serverHandshakeState) processClientHello() error {
   167  	c := hs.c
   168  
   169  	hs.hello = new(serverHelloMsg)
   170  	hs.hello.vers = c.vers
   171  
   172  	foundCompression := false
   173  	// We only support null compression, so check that the client offered it.
   174  	for _, compression := range hs.clientHello.compressionMethods {
   175  		if compression == compressionNone {
   176  			foundCompression = true
   177  			break
   178  		}
   179  	}
   180  
   181  	if !foundCompression {
   182  		c.sendAlert(alertHandshakeFailure)
   183  		return errors.New("tls: client does not support uncompressed connections")
   184  	}
   185  
   186  	hs.hello.random = make([]byte, 32)
   187  	serverRandom := hs.hello.random
   188  	// Downgrade protection canaries. See RFC 8446, Section 4.1.3.
   189  	maxVers := c.config.maxSupportedVersion()
   190  	if maxVers >= VersionTLS12 && c.vers < maxVers || testingOnlyForceDowngradeCanary {
   191  		if c.vers == VersionTLS12 {
   192  			copy(serverRandom[24:], downgradeCanaryTLS12)
   193  		} else {
   194  			copy(serverRandom[24:], downgradeCanaryTLS11)
   195  		}
   196  		serverRandom = serverRandom[:24]
   197  	}
   198  	_, err := io.ReadFull(c.config.rand(), serverRandom)
   199  	if err != nil {
   200  		c.sendAlert(alertInternalError)
   201  		return err
   202  	}
   203  
   204  	if len(hs.clientHello.secureRenegotiation) != 0 {
   205  		c.sendAlert(alertHandshakeFailure)
   206  		return errors.New("tls: initial handshake had non-empty renegotiation extension")
   207  	}
   208  
   209  	hs.hello.secureRenegotiationSupported = hs.clientHello.secureRenegotiationSupported
   210  	hs.hello.compressionMethod = compressionNone
   211  	if len(hs.clientHello.serverName) > 0 {
   212  		c.serverName = hs.clientHello.serverName
   213  	}
   214  
   215  	if len(hs.clientHello.alpnProtocols) > 0 {
   216  		if selectedProto, fallback := mutualProtocol(hs.clientHello.alpnProtocols, c.config.NextProtos); !fallback {
   217  			hs.hello.alpnProtocol = selectedProto
   218  			c.clientProtocol = selectedProto
   219  		}
   220  	}
   221  
   222  	hs.cert, err = c.config.getCertificate(clientHelloInfo(c, hs.clientHello))
   223  	if err != nil {
   224  		if err == errNoCertificates {
   225  			c.sendAlert(alertUnrecognizedName)
   226  		} else {
   227  			c.sendAlert(alertInternalError)
   228  		}
   229  		return err
   230  	}
   231  	if hs.clientHello.scts {
   232  		hs.hello.scts = hs.cert.SignedCertificateTimestamps
   233  	}
   234  
   235  	hs.ecdheOk = supportsECDHE(c.config, hs.clientHello.supportedCurves, hs.clientHello.supportedPoints)
   236  
   237  	if hs.ecdheOk {
   238  		// Although omitting the ec_point_formats extension is permitted, some
   239  		// old OpenSSL version will refuse to handshake if not present.
   240  		//
   241  		// Per RFC 4492, section 5.1.2, implementations MUST support the
   242  		// uncompressed point format. See golang.org/issue/31943.
   243  		hs.hello.supportedPoints = []uint8{pointFormatUncompressed}
   244  	}
   245  
   246  	if priv, ok := hs.cert.PrivateKey.(crypto.Signer); ok {
   247  		switch priv.Public().(type) {
   248  		case *ecdsa.PublicKey:
   249  			hs.ecSignOk = true
   250  		case ed25519.PublicKey:
   251  			hs.ecSignOk = true
   252  		case *rsa.PublicKey:
   253  			hs.rsaSignOk = true
   254  		default:
   255  			c.sendAlert(alertInternalError)
   256  			return fmt.Errorf("tls: unsupported signing key type (%T)", priv.Public())
   257  		}
   258  	}
   259  	if priv, ok := hs.cert.PrivateKey.(crypto.Decrypter); ok {
   260  		switch priv.Public().(type) {
   261  		case *rsa.PublicKey:
   262  			hs.rsaDecryptOk = true
   263  		default:
   264  			c.sendAlert(alertInternalError)
   265  			return fmt.Errorf("tls: unsupported decryption key type (%T)", priv.Public())
   266  		}
   267  	}
   268  
   269  	return nil
   270  }
   271  
   272  // supportsECDHE returns whether ECDHE key exchanges can be used with this
   273  // pre-TLS 1.3 client.
   274  func supportsECDHE(c *Config, supportedCurves []CurveID, supportedPoints []uint8) bool {
   275  	supportsCurve := false
   276  	for _, curve := range supportedCurves {
   277  		if c.supportsCurve(curve) {
   278  			supportsCurve = true
   279  			break
   280  		}
   281  	}
   282  
   283  	supportsPointFormat := false
   284  	for _, pointFormat := range supportedPoints {
   285  		if pointFormat == pointFormatUncompressed {
   286  			supportsPointFormat = true
   287  			break
   288  		}
   289  	}
   290  
   291  	return supportsCurve && supportsPointFormat
   292  }
   293  
   294  func (hs *serverHandshakeState) pickCipherSuite() error {
   295  	c := hs.c
   296  
   297  	var preferenceList, supportedList []uint16
   298  	if c.config.PreferServerCipherSuites {
   299  		preferenceList = c.config.cipherSuites()
   300  		supportedList = hs.clientHello.cipherSuites
   301  	} else {
   302  		preferenceList = hs.clientHello.cipherSuites
   303  		supportedList = c.config.cipherSuites()
   304  	}
   305  
   306  	hs.suite = selectCipherSuite(preferenceList, supportedList, hs.cipherSuiteOk)
   307  	if hs.suite == nil {
   308  		c.sendAlert(alertHandshakeFailure)
   309  		return errors.New("tls: no cipher suite supported by both client and server")
   310  	}
   311  	c.cipherSuite = hs.suite.id
   312  
   313  	for _, id := range hs.clientHello.cipherSuites {
   314  		if id == TLS_FALLBACK_SCSV {
   315  			// The client is doing a fallback connection. See RFC 7507.
   316  			if hs.clientHello.vers < c.config.maxSupportedVersion() {
   317  				c.sendAlert(alertInappropriateFallback)
   318  				return errors.New("tls: client using inappropriate protocol fallback")
   319  			}
   320  			break
   321  		}
   322  	}
   323  
   324  	return nil
   325  }
   326  
   327  func (hs *serverHandshakeState) cipherSuiteOk(c *cipherSuite) bool {
   328  	if c.flags&suiteECDHE != 0 {
   329  		if !hs.ecdheOk {
   330  			return false
   331  		}
   332  		if c.flags&suiteECSign != 0 {
   333  			if !hs.ecSignOk {
   334  				return false
   335  			}
   336  		} else if !hs.rsaSignOk {
   337  			return false
   338  		}
   339  	} else if !hs.rsaDecryptOk {
   340  		return false
   341  	}
   342  	if hs.c.vers < VersionTLS12 && c.flags&suiteTLS12 != 0 {
   343  		return false
   344  	}
   345  	return true
   346  }
   347  
   348  // checkForResumption reports whether we should perform resumption on this connection.
   349  func (hs *serverHandshakeState) checkForResumption() bool {
   350  	c := hs.c
   351  
   352  	if c.config.SessionTicketsDisabled {
   353  		return false
   354  	}
   355  
   356  	plaintext, usedOldKey := c.decryptTicket(hs.clientHello.sessionTicket)
   357  	if plaintext == nil {
   358  		return false
   359  	}
   360  	hs.sessionState = &sessionState{usedOldKey: usedOldKey}
   361  	ok := hs.sessionState.unmarshal(plaintext)
   362  	if !ok {
   363  		return false
   364  	}
   365  
   366  	createdAt := time.Unix(int64(hs.sessionState.createdAt), 0)
   367  	if c.config.time().Sub(createdAt) > maxSessionTicketLifetime {
   368  		return false
   369  	}
   370  
   371  	// Never resume a session for a different TLS version.
   372  	if c.vers != hs.sessionState.vers {
   373  		return false
   374  	}
   375  
   376  	cipherSuiteOk := false
   377  	// Check that the client is still offering the ciphersuite in the session.
   378  	for _, id := range hs.clientHello.cipherSuites {
   379  		if id == hs.sessionState.cipherSuite {
   380  			cipherSuiteOk = true
   381  			break
   382  		}
   383  	}
   384  	if !cipherSuiteOk {
   385  		return false
   386  	}
   387  
   388  	// Check that we also support the ciphersuite from the session.
   389  	hs.suite = selectCipherSuite([]uint16{hs.sessionState.cipherSuite},
   390  		c.config.cipherSuites(), hs.cipherSuiteOk)
   391  	if hs.suite == nil {
   392  		return false
   393  	}
   394  
   395  	sessionHasClientCerts := len(hs.sessionState.certificates) != 0
   396  	needClientCerts := requiresClientCert(c.config.ClientAuth)
   397  	if needClientCerts && !sessionHasClientCerts {
   398  		return false
   399  	}
   400  	if sessionHasClientCerts && c.config.ClientAuth == NoClientCert {
   401  		return false
   402  	}
   403  
   404  	return true
   405  }
   406  
   407  func (hs *serverHandshakeState) doResumeHandshake() error {
   408  	c := hs.c
   409  
   410  	hs.hello.cipherSuite = hs.suite.id
   411  	c.cipherSuite = hs.suite.id
   412  	// We echo the client's session ID in the ServerHello to let it know
   413  	// that we're doing a resumption.
   414  	hs.hello.sessionId = hs.clientHello.sessionId
   415  	hs.hello.ticketSupported = hs.sessionState.usedOldKey
   416  	hs.finishedHash = newFinishedHash(c.vers, hs.suite)
   417  	hs.finishedHash.discardHandshakeBuffer()
   418  	hs.finishedHash.Write(hs.clientHello.marshal())
   419  	hs.finishedHash.Write(hs.hello.marshal())
   420  	if _, err := c.writeRecord(recordTypeHandshake, hs.hello.marshal()); err != nil {
   421  		return err
   422  	}
   423  
   424  	if err := c.processCertsFromClient(Certificate{
   425  		Certificate: hs.sessionState.certificates,
   426  	}); err != nil {
   427  		return err
   428  	}
   429  
   430  	if c.config.VerifyConnection != nil {
   431  		if err := c.config.VerifyConnection(c.connectionStateLocked()); err != nil {
   432  			c.sendAlert(alertBadCertificate)
   433  			return err
   434  		}
   435  	}
   436  
   437  	hs.masterSecret = hs.sessionState.masterSecret
   438  
   439  	return nil
   440  }
   441  
   442  func (hs *serverHandshakeState) doFullHandshake() error {
   443  	c := hs.c
   444  
   445  	if hs.clientHello.ocspStapling && len(hs.cert.OCSPStaple) > 0 {
   446  		hs.hello.ocspStapling = true
   447  	}
   448  
   449  	hs.hello.ticketSupported = hs.clientHello.ticketSupported && !c.config.SessionTicketsDisabled
   450  	hs.hello.cipherSuite = hs.suite.id
   451  
   452  	hs.finishedHash = newFinishedHash(hs.c.vers, hs.suite)
   453  	if c.config.ClientAuth == NoClientCert {
   454  		// No need to keep a full record of the handshake if client
   455  		// certificates won't be used.
   456  		hs.finishedHash.discardHandshakeBuffer()
   457  	}
   458  	hs.finishedHash.Write(hs.clientHello.marshal())
   459  	hs.finishedHash.Write(hs.hello.marshal())
   460  	if _, err := c.writeRecord(recordTypeHandshake, hs.hello.marshal()); err != nil {
   461  		return err
   462  	}
   463  
   464  	certMsg := new(certificateMsg)
   465  	certMsg.certificates = hs.cert.Certificate
   466  	hs.finishedHash.Write(certMsg.marshal())
   467  	if _, err := c.writeRecord(recordTypeHandshake, certMsg.marshal()); err != nil {
   468  		return err
   469  	}
   470  
   471  	if hs.hello.ocspStapling {
   472  		certStatus := new(certificateStatusMsg)
   473  		certStatus.response = hs.cert.OCSPStaple
   474  		hs.finishedHash.Write(certStatus.marshal())
   475  		if _, err := c.writeRecord(recordTypeHandshake, certStatus.marshal()); err != nil {
   476  			return err
   477  		}
   478  	}
   479  
   480  	keyAgreement := hs.suite.ka(c.vers)
   481  	skx, err := keyAgreement.generateServerKeyExchange(c.config, hs.cert, hs.clientHello, hs.hello)
   482  	if err != nil {
   483  		c.sendAlert(alertHandshakeFailure)
   484  		return err
   485  	}
   486  	if skx != nil {
   487  		hs.finishedHash.Write(skx.marshal())
   488  		if _, err := c.writeRecord(recordTypeHandshake, skx.marshal()); err != nil {
   489  			return err
   490  		}
   491  	}
   492  
   493  	var certReq *certificateRequestMsg
   494  	if c.config.ClientAuth >= RequestClientCert {
   495  		// Request a client certificate
   496  		certReq = new(certificateRequestMsg)
   497  		certReq.certificateTypes = []byte{
   498  			byte(certTypeRSASign),
   499  			byte(certTypeECDSASign),
   500  		}
   501  		if c.vers >= VersionTLS12 {
   502  			certReq.hasSignatureAlgorithm = true
   503  			certReq.supportedSignatureAlgorithms = supportedSignatureAlgorithms
   504  		}
   505  
   506  		// An empty list of certificateAuthorities signals to
   507  		// the client that it may send any certificate in response
   508  		// to our request. When we know the CAs we trust, then
   509  		// we can send them down, so that the client can choose
   510  		// an appropriate certificate to give to us.
   511  		if c.config.ClientCAs != nil {
   512  			certReq.certificateAuthorities = c.config.ClientCAs.Subjects()
   513  		}
   514  		hs.finishedHash.Write(certReq.marshal())
   515  		if _, err := c.writeRecord(recordTypeHandshake, certReq.marshal()); err != nil {
   516  			return err
   517  		}
   518  	}
   519  
   520  	helloDone := new(serverHelloDoneMsg)
   521  	hs.finishedHash.Write(helloDone.marshal())
   522  	if _, err := c.writeRecord(recordTypeHandshake, helloDone.marshal()); err != nil {
   523  		return err
   524  	}
   525  
   526  	if _, err := c.flush(); err != nil {
   527  		return err
   528  	}
   529  
   530  	var pub crypto.PublicKey // public key for client auth, if any
   531  
   532  	msg, err := c.readHandshake()
   533  	if err != nil {
   534  		return err
   535  	}
   536  
   537  	// If we requested a client certificate, then the client must send a
   538  	// certificate message, even if it's empty.
   539  	if c.config.ClientAuth >= RequestClientCert {
   540  		certMsg, ok := msg.(*certificateMsg)
   541  		if !ok {
   542  			c.sendAlert(alertUnexpectedMessage)
   543  			return unexpectedMessageError(certMsg, msg)
   544  		}
   545  		hs.finishedHash.Write(certMsg.marshal())
   546  
   547  		if err := c.processCertsFromClient(Certificate{
   548  			Certificate: certMsg.certificates,
   549  		}); err != nil {
   550  			return err
   551  		}
   552  		if len(certMsg.certificates) != 0 {
   553  			pub = c.peerCertificates[0].PublicKey
   554  		}
   555  
   556  		msg, err = c.readHandshake()
   557  		if err != nil {
   558  			return err
   559  		}
   560  	}
   561  	if c.config.VerifyConnection != nil {
   562  		if err := c.config.VerifyConnection(c.connectionStateLocked()); err != nil {
   563  			c.sendAlert(alertBadCertificate)
   564  			return err
   565  		}
   566  	}
   567  
   568  	// Get client key exchange
   569  	ckx, ok := msg.(*clientKeyExchangeMsg)
   570  	if !ok {
   571  		c.sendAlert(alertUnexpectedMessage)
   572  		return unexpectedMessageError(ckx, msg)
   573  	}
   574  	hs.finishedHash.Write(ckx.marshal())
   575  
   576  	preMasterSecret, err := keyAgreement.processClientKeyExchange(c.config, hs.cert, ckx, c.vers)
   577  	if err != nil {
   578  		c.sendAlert(alertHandshakeFailure)
   579  		return err
   580  	}
   581  	hs.masterSecret = masterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret, hs.clientHello.random, hs.hello.random)
   582  	if err := c.config.writeKeyLog(keyLogLabelTLS12, hs.clientHello.random, hs.masterSecret); err != nil {
   583  		c.sendAlert(alertInternalError)
   584  		return err
   585  	}
   586  
   587  	// If we received a client cert in response to our certificate request message,
   588  	// the client will send us a certificateVerifyMsg immediately after the
   589  	// clientKeyExchangeMsg. This message is a digest of all preceding
   590  	// handshake-layer messages that is signed using the private key corresponding
   591  	// to the client's certificate. This allows us to verify that the client is in
   592  	// possession of the private key of the certificate.
   593  	if len(c.peerCertificates) > 0 {
   594  		msg, err = c.readHandshake()
   595  		if err != nil {
   596  			return err
   597  		}
   598  		certVerify, ok := msg.(*certificateVerifyMsg)
   599  		if !ok {
   600  			c.sendAlert(alertUnexpectedMessage)
   601  			return unexpectedMessageError(certVerify, msg)
   602  		}
   603  
   604  		var sigType uint8
   605  		var sigHash crypto.Hash
   606  		if c.vers >= VersionTLS12 {
   607  			if !isSupportedSignatureAlgorithm(certVerify.signatureAlgorithm, certReq.supportedSignatureAlgorithms) {
   608  				c.sendAlert(alertIllegalParameter)
   609  				return errors.New("tls: client certificate used with invalid signature algorithm")
   610  			}
   611  			sigType, sigHash, err = typeAndHashFromSignatureScheme(certVerify.signatureAlgorithm)
   612  			if err != nil {
   613  				return c.sendAlert(alertInternalError)
   614  			}
   615  		} else {
   616  			sigType, sigHash, err = legacyTypeAndHashFromPublicKey(pub)
   617  			if err != nil {
   618  				c.sendAlert(alertIllegalParameter)
   619  				return err
   620  			}
   621  		}
   622  
   623  		signed := hs.finishedHash.hashForClientCertificate(sigType, sigHash, hs.masterSecret)
   624  		if err := verifyHandshakeSignature(sigType, pub, sigHash, signed, certVerify.signature); err != nil {
   625  			c.sendAlert(alertDecryptError)
   626  			return errors.New("tls: invalid signature by the client certificate: " + err.Error())
   627  		}
   628  
   629  		hs.finishedHash.Write(certVerify.marshal())
   630  	}
   631  
   632  	hs.finishedHash.discardHandshakeBuffer()
   633  
   634  	return nil
   635  }
   636  
   637  func (hs *serverHandshakeState) establishKeys() error {
   638  	c := hs.c
   639  
   640  	clientMAC, serverMAC, clientKey, serverKey, clientIV, serverIV :=
   641  		keysFromMasterSecret(c.vers, hs.suite, hs.masterSecret, hs.clientHello.random, hs.hello.random, hs.suite.macLen, hs.suite.keyLen, hs.suite.ivLen)
   642  
   643  	var clientCipher, serverCipher interface{}
   644  	var clientHash, serverHash macFunction
   645  
   646  	if hs.suite.aead == nil {
   647  		clientCipher = hs.suite.cipher(clientKey, clientIV, true /* for reading */)
   648  		clientHash = hs.suite.mac(c.vers, clientMAC)
   649  		serverCipher = hs.suite.cipher(serverKey, serverIV, false /* not for reading */)
   650  		serverHash = hs.suite.mac(c.vers, serverMAC)
   651  	} else {
   652  		clientCipher = hs.suite.aead(clientKey, clientIV)
   653  		serverCipher = hs.suite.aead(serverKey, serverIV)
   654  	}
   655  
   656  	c.in.prepareCipherSpec(c.vers, clientCipher, clientHash)
   657  	c.out.prepareCipherSpec(c.vers, serverCipher, serverHash)
   658  
   659  	return nil
   660  }
   661  
   662  func (hs *serverHandshakeState) readFinished(out []byte) error {
   663  	c := hs.c
   664  
   665  	if err := c.readChangeCipherSpec(); err != nil {
   666  		return err
   667  	}
   668  
   669  	msg, err := c.readHandshake()
   670  	if err != nil {
   671  		return err
   672  	}
   673  	clientFinished, ok := msg.(*finishedMsg)
   674  	if !ok {
   675  		c.sendAlert(alertUnexpectedMessage)
   676  		return unexpectedMessageError(clientFinished, msg)
   677  	}
   678  
   679  	verify := hs.finishedHash.clientSum(hs.masterSecret)
   680  	if len(verify) != len(clientFinished.verifyData) ||
   681  		subtle.ConstantTimeCompare(verify, clientFinished.verifyData) != 1 {
   682  		c.sendAlert(alertHandshakeFailure)
   683  		return errors.New("tls: client's Finished message is incorrect")
   684  	}
   685  
   686  	hs.finishedHash.Write(clientFinished.marshal())
   687  	copy(out, verify)
   688  	return nil
   689  }
   690  
   691  func (hs *serverHandshakeState) sendSessionTicket() error {
   692  	// ticketSupported is set in a resumption handshake if the
   693  	// ticket from the client was encrypted with an old session
   694  	// ticket key and thus a refreshed ticket should be sent.
   695  	if !hs.hello.ticketSupported {
   696  		return nil
   697  	}
   698  
   699  	c := hs.c
   700  	m := new(newSessionTicketMsg)
   701  
   702  	createdAt := uint64(c.config.time().Unix())
   703  	if hs.sessionState != nil {
   704  		// If this is re-wrapping an old key, then keep
   705  		// the original time it was created.
   706  		createdAt = hs.sessionState.createdAt
   707  	}
   708  
   709  	var certsFromClient [][]byte
   710  	for _, cert := range c.peerCertificates {
   711  		certsFromClient = append(certsFromClient, cert.Raw)
   712  	}
   713  	state := sessionState{
   714  		vers:         c.vers,
   715  		cipherSuite:  hs.suite.id,
   716  		createdAt:    createdAt,
   717  		masterSecret: hs.masterSecret,
   718  		certificates: certsFromClient,
   719  	}
   720  	var err error
   721  	m.ticket, err = c.encryptTicket(state.marshal())
   722  	if err != nil {
   723  		return err
   724  	}
   725  
   726  	hs.finishedHash.Write(m.marshal())
   727  	if _, err := c.writeRecord(recordTypeHandshake, m.marshal()); err != nil {
   728  		return err
   729  	}
   730  
   731  	return nil
   732  }
   733  
   734  func (hs *serverHandshakeState) sendFinished(out []byte) error {
   735  	c := hs.c
   736  
   737  	if _, err := c.writeRecord(recordTypeChangeCipherSpec, []byte{1}); err != nil {
   738  		return err
   739  	}
   740  
   741  	finished := new(finishedMsg)
   742  	finished.verifyData = hs.finishedHash.serverSum(hs.masterSecret)
   743  	hs.finishedHash.Write(finished.marshal())
   744  	if _, err := c.writeRecord(recordTypeHandshake, finished.marshal()); err != nil {
   745  		return err
   746  	}
   747  
   748  	copy(out, finished.verifyData)
   749  
   750  	return nil
   751  }
   752  
   753  // processCertsFromClient takes a chain of client certificates either from a
   754  // Certificates message or from a sessionState and verifies them. It returns
   755  // the public key of the leaf certificate.
   756  func (c *Conn) processCertsFromClient(certificate Certificate) error {
   757  	certificates := certificate.Certificate
   758  	certs := make([]*x509.Certificate, len(certificates))
   759  	var err error
   760  	for i, asn1Data := range certificates {
   761  		if certs[i], err = x509.ParseCertificate(asn1Data); err != nil {
   762  			c.sendAlert(alertBadCertificate)
   763  			return errors.New("tls: failed to parse client certificate: " + err.Error())
   764  		}
   765  	}
   766  
   767  	if len(certs) == 0 && requiresClientCert(c.config.ClientAuth) {
   768  		c.sendAlert(alertBadCertificate)
   769  		return errors.New("tls: client didn't provide a certificate")
   770  	}
   771  
   772  	if c.config.ClientAuth >= VerifyClientCertIfGiven && len(certs) > 0 {
   773  		opts := x509.VerifyOptions{
   774  			Roots:         c.config.ClientCAs,
   775  			CurrentTime:   c.config.time(),
   776  			Intermediates: x509.NewCertPool(),
   777  			KeyUsages:     []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth},
   778  		}
   779  
   780  		for _, cert := range certs[1:] {
   781  			opts.Intermediates.AddCert(cert)
   782  		}
   783  
   784  		chains, err := certs[0].Verify(opts)
   785  		if err != nil {
   786  			c.sendAlert(alertBadCertificate)
   787  			return errors.New("tls: failed to verify client certificate: " + err.Error())
   788  		}
   789  
   790  		c.verifiedChains = chains
   791  	}
   792  
   793  	c.peerCertificates = certs
   794  	c.ocspResponse = certificate.OCSPStaple
   795  	c.scts = certificate.SignedCertificateTimestamps
   796  
   797  	if len(certs) > 0 {
   798  		switch certs[0].PublicKey.(type) {
   799  		case *ecdsa.PublicKey, *rsa.PublicKey, ed25519.PublicKey:
   800  		default:
   801  			c.sendAlert(alertUnsupportedCertificate)
   802  			return fmt.Errorf("tls: client certificate contains an unsupported public key of type %T", certs[0].PublicKey)
   803  		}
   804  	}
   805  
   806  	if c.config.VerifyPeerCertificate != nil {
   807  		if err := c.config.VerifyPeerCertificate(certificates, c.verifiedChains); err != nil {
   808  			c.sendAlert(alertBadCertificate)
   809  			return err
   810  		}
   811  	}
   812  
   813  	return nil
   814  }
   815  
   816  func clientHelloInfo(c *Conn, clientHello *clientHelloMsg) *ClientHelloInfo {
   817  	supportedVersions := clientHello.supportedVersions
   818  	if len(clientHello.supportedVersions) == 0 {
   819  		supportedVersions = supportedVersionsFromMax(clientHello.vers)
   820  	}
   821  
   822  	return &ClientHelloInfo{
   823  		CipherSuites:      clientHello.cipherSuites,
   824  		ServerName:        clientHello.serverName,
   825  		SupportedCurves:   clientHello.supportedCurves,
   826  		SupportedPoints:   clientHello.supportedPoints,
   827  		SignatureSchemes:  clientHello.supportedSignatureAlgorithms,
   828  		SupportedProtos:   clientHello.alpnProtocols,
   829  		SupportedVersions: supportedVersions,
   830  		Conn:              c.conn,
   831  		config:            c.config,
   832  	}
   833  }
   834  

View as plain text