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

View as plain text