...
Run Format

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

View as plain text