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.
19 // serverHandshakeState contains details of a server handshake in progress.
20 // It's discarded once the handshake has completed.
21 type serverHandshakeState struct {
23 clientHello *clientHelloMsg
30 sessionState *sessionState
31 finishedHash finishedHash
33 certsFromClient [][]byte
35 cachedClientHelloInfo *ClientHelloInfo
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) })
44 hs := serverHandshakeState{
47 isResume, err := hs.readClientHello()
52 // For an overview of TLS handshaking, see https://tools.ietf.org/html/rfc5246#section-7.3
55 // The client has included a session ticket and so we do an abbreviated handshake.
56 if err := hs.doResumeHandshake(); err != nil {
59 if err := hs.establishKeys(); err != nil {
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 {
70 if err := hs.sendFinished(c.serverFinished[:]); err != nil {
73 if _, err := c.flush(); err != nil {
76 c.clientFinishedIsFirst = false
77 if err := hs.readFinished(nil); err != nil {
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 {
87 if err := hs.establishKeys(); err != nil {
90 if err := hs.readFinished(c.clientFinished[:]); err != nil {
93 c.clientFinishedIsFirst = true
95 if err := hs.sendSessionTicket(); err != nil {
98 if err := hs.sendFinished(nil); err != nil {
101 if _, err := c.flush(); err != nil {
106 c.ekm = ekmFromMasterSecret(c.vers, hs.suite, hs.masterSecret, hs.clientHello.random, hs.hello.random)
107 c.handshakeComplete = true
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) {
117 msg, err := c.readHandshake()
122 hs.clientHello, ok = msg.(*clientHelloMsg)
124 c.sendAlert(alertUnexpectedMessage)
125 return false, unexpectedMessageError(hs.clientHello, msg)
128 if c.config.GetConfigForClient != nil {
129 if newConfig, err := c.config.GetConfigForClient(hs.clientHelloInfo()); err != nil {
130 c.sendAlert(alertInternalError)
132 } else if newConfig != nil {
133 newConfig.serverInitOnce.Do(func() { newConfig.serverInit(c.config) })
138 c.vers, ok = c.config.mutualVersion(hs.clientHello.vers)
140 c.sendAlert(alertProtocolVersion)
141 return false, fmt.Errorf("tls: client offered an unsupported, maximum protocol version of %x", hs.clientHello.vers)
145 hs.hello = new(serverHelloMsg)
147 supportedCurve := false
148 preferredCurves := c.config.curvePreferences()
150 for _, curve := range hs.clientHello.supportedCurves {
151 for _, supported := range preferredCurves {
152 if supported == curve {
153 supportedCurve = true
159 supportedPointFormat := false
160 for _, pointFormat := range hs.clientHello.supportedPoints {
161 if pointFormat == pointFormatUncompressed {
162 supportedPointFormat = true
166 hs.ellipticOk = supportedCurve && supportedPointFormat
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
177 if !foundCompression {
178 c.sendAlert(alertHandshakeFailure)
179 return false, errors.New("tls: client does not support uncompressed connections")
182 hs.hello.vers = c.vers
183 hs.hello.random = make([]byte, 32)
184 _, err = io.ReadFull(c.config.rand(), hs.hello.random)
186 c.sendAlert(alertInternalError)
190 if len(hs.clientHello.secureRenegotiation) != 0 {
191 c.sendAlert(alertHandshakeFailure)
192 return false, errors.New("tls: initial handshake had non-empty renegotiation extension")
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
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
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
217 hs.cert, err = c.config.getCertificate(hs.clientHelloInfo())
219 c.sendAlert(alertInternalError)
222 if hs.clientHello.scts {
223 hs.hello.scts = hs.cert.SignedCertificateTimestamps
226 if priv, ok := hs.cert.PrivateKey.(crypto.Signer); ok {
227 switch priv.Public().(type) {
228 case *ecdsa.PublicKey:
233 c.sendAlert(alertInternalError)
234 return false, fmt.Errorf("tls: unsupported signing key type (%T)", priv.Public())
237 if priv, ok := hs.cert.PrivateKey.(crypto.Decrypter); ok {
238 switch priv.Public().(type) {
240 hs.rsaDecryptOk = true
242 c.sendAlert(alertInternalError)
243 return false, fmt.Errorf("tls: unsupported decryption key type (%T)", priv.Public())
247 if hs.checkForResumption() {
251 var preferenceList, supportedList []uint16
252 if c.config.PreferServerCipherSuites {
253 preferenceList = c.config.cipherSuites()
254 supportedList = hs.clientHello.cipherSuites
256 preferenceList = hs.clientHello.cipherSuites
257 supportedList = c.config.cipherSuites()
260 for _, id := range preferenceList {
261 if hs.setCipherSuite(id, supportedList, c.vers) {
267 c.sendAlert(alertHandshakeFailure)
268 return false, errors.New("tls: no cipher suite supported by both client and server")
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")
286 // checkForResumption reports whether we should perform resumption on this connection.
287 func (hs *serverHandshakeState) checkForResumption() bool {
290 if c.config.SessionTicketsDisabled {
295 var sessionTicket = append([]uint8{}, hs.clientHello.sessionTicket...)
296 if hs.sessionState, ok = c.decryptTicket(sessionTicket); !ok {
300 // Never resume a session for a different TLS version.
301 if c.vers != hs.sessionState.vers {
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 {
317 // Check that we also support the ciphersuite from the session.
318 if !hs.setCipherSuite(hs.sessionState.cipherSuite, c.config.cipherSuites(), hs.sessionState.vers) {
322 sessionHasClientCerts := len(hs.sessionState.certificates) != 0
323 needClientCerts := c.config.ClientAuth == RequireAnyClientCert || c.config.ClientAuth == RequireAndVerifyClientCert
324 if needClientCerts && !sessionHasClientCerts {
327 if sessionHasClientCerts && c.config.ClientAuth == NoClientCert {
334 func (hs *serverHandshakeState) doResumeHandshake() error {
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 {
350 if len(hs.sessionState.certificates) > 0 {
351 if _, err := hs.processCertsFromClient(hs.sessionState.certificates); err != nil {
356 hs.masterSecret = hs.sessionState.masterSecret
361 func (hs *serverHandshakeState) doFullHandshake() error {
364 if hs.clientHello.ocspStapling && len(hs.cert.OCSPStaple) > 0 {
365 hs.hello.ocspStapling = true
368 hs.hello.ticketSupported = hs.clientHello.ticketSupported && !c.config.SessionTicketsDisabled
369 hs.hello.cipherSuite = hs.suite.id
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()
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 {
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 {
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 {
400 keyAgreement := hs.suite.ka(c.vers)
401 skx, err := keyAgreement.generateServerKeyExchange(c.config, hs.cert, hs.clientHello, hs.hello)
403 c.sendAlert(alertHandshakeFailure)
407 hs.finishedHash.Write(skx.marshal())
408 if _, err := c.writeRecord(recordTypeHandshake, skx.marshal()); err != nil {
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),
420 if c.vers >= VersionTLS12 {
421 certReq.hasSignatureAndHash = true
422 certReq.supportedSignatureAlgorithms = supportedSignatureAlgorithms()
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()
433 hs.finishedHash.Write(certReq.marshal())
434 if _, err := c.writeRecord(recordTypeHandshake, certReq.marshal()); err != nil {
439 helloDone := new(serverHelloDoneMsg)
440 hs.finishedHash.Write(helloDone.marshal())
441 if _, err := c.writeRecord(recordTypeHandshake, helloDone.marshal()); err != nil {
445 if _, err := c.flush(); err != nil {
449 var pub crypto.PublicKey // public key for client auth, if any
451 msg, err := c.readHandshake()
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)
464 hs.finishedHash.Write(certMsg.marshal())
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")
475 pub, err = hs.processCertsFromClient(certMsg.certificates)
480 msg, err = c.readHandshake()
486 // Get client key exchange
487 ckx, ok := msg.(*clientKeyExchangeMsg)
489 c.sendAlert(alertUnexpectedMessage)
490 return unexpectedMessageError(ckx, msg)
492 hs.finishedHash.Write(ckx.marshal())
494 preMasterSecret, err := keyAgreement.processClientKeyExchange(c.config, hs.cert, ckx, c.vers)
496 c.sendAlert(alertHandshakeFailure)
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)
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()
516 certVerify, ok := msg.(*certificateVerifyMsg)
518 c.sendAlert(alertUnexpectedMessage)
519 return unexpectedMessageError(certVerify, msg)
522 // Determine the signature type.
523 var signatureAlgorithm SignatureScheme
525 if certVerify.hasSignatureAndHash {
526 signatureAlgorithm = certVerify.signatureAlgorithm
527 if !isSupportedSignatureAlgorithm(signatureAlgorithm, supportedSignatureAlgorithms()) {
528 return errors.New("tls: unsupported hash function for client certificate")
530 sigType = signatureFromSignatureScheme(signatureAlgorithm)
532 // Before TLS 1.2 the signature algorithm was implicit
533 // from the key type, and only one hash per signature
534 // algorithm was possible. Leave signatureAlgorithm
537 case *ecdsa.PublicKey:
538 sigType = signatureECDSA
540 sigType = signatureRSA
544 switch key := pub.(type) {
545 case *ecdsa.PublicKey:
546 if sigType != signatureECDSA {
547 err = errors.New("tls: bad signature type for client's ECDSA certificate")
550 ecdsaSig := new(ecdsaSignature)
551 if _, err = asn1.Unmarshal(certVerify.signature, ecdsaSig); err != nil {
554 if ecdsaSig.R.Sign() <= 0 || ecdsaSig.S.Sign() <= 0 {
555 err = errors.New("tls: ECDSA signature contained zero or negative values")
559 if digest, _, err = hs.finishedHash.hashForClientCertificate(sigType, signatureAlgorithm, hs.masterSecret); err != nil {
562 if !ecdsa.Verify(key, digest, ecdsaSig.R, ecdsaSig.S) {
563 err = errors.New("tls: ECDSA verification failure")
566 if sigType != signatureRSA {
567 err = errors.New("tls: bad signature type for client's RSA certificate")
571 var hashFunc crypto.Hash
572 if digest, hashFunc, err = hs.finishedHash.hashForClientCertificate(sigType, signatureAlgorithm, hs.masterSecret); err != nil {
575 err = rsa.VerifyPKCS1v15(key, hashFunc, digest, certVerify.signature)
578 c.sendAlert(alertBadCertificate)
579 return errors.New("tls: could not validate signature of connection nonces: " + err.Error())
582 hs.finishedHash.Write(certVerify.marshal())
585 hs.finishedHash.discardHandshakeBuffer()
590 func (hs *serverHandshakeState) establishKeys() error {
593 clientMAC, serverMAC, clientKey, serverKey, clientIV, serverIV :=
594 keysFromMasterSecret(c.vers, hs.suite, hs.masterSecret, hs.clientHello.random, hs.hello.random, hs.suite.macLen, hs.suite.keyLen, hs.suite.ivLen)
596 var clientCipher, serverCipher interface{}
597 var clientHash, serverHash macFunction
599 if hs.suite.aead == nil {
600 clientCipher = hs.suite.cipher(clientKey, clientIV, true /* for reading */)
601 clientHash = hs.suite.mac(c.vers, clientMAC)
602 serverCipher = hs.suite.cipher(serverKey, serverIV, false /* not for reading */)
603 serverHash = hs.suite.mac(c.vers, serverMAC)
605 clientCipher = hs.suite.aead(clientKey, clientIV)
606 serverCipher = hs.suite.aead(serverKey, serverIV)
609 c.in.prepareCipherSpec(c.vers, clientCipher, clientHash)
610 c.out.prepareCipherSpec(c.vers, serverCipher, serverHash)
615 func (hs *serverHandshakeState) readFinished(out []byte) error {
618 c.readRecord(recordTypeChangeCipherSpec)
623 if hs.hello.nextProtoNeg {
624 msg, err := c.readHandshake()
628 nextProto, ok := msg.(*nextProtoMsg)
630 c.sendAlert(alertUnexpectedMessage)
631 return unexpectedMessageError(nextProto, msg)
633 hs.finishedHash.Write(nextProto.marshal())
634 c.clientProtocol = nextProto.proto
637 msg, err := c.readHandshake()
641 clientFinished, ok := msg.(*finishedMsg)
643 c.sendAlert(alertUnexpectedMessage)
644 return unexpectedMessageError(clientFinished, msg)
647 verify := hs.finishedHash.clientSum(hs.masterSecret)
648 if len(verify) != len(clientFinished.verifyData) ||
649 subtle.ConstantTimeCompare(verify, clientFinished.verifyData) != 1 {
650 c.sendAlert(alertHandshakeFailure)
651 return errors.New("tls: client's Finished message is incorrect")
654 hs.finishedHash.Write(clientFinished.marshal())
659 func (hs *serverHandshakeState) sendSessionTicket() error {
660 if !hs.hello.ticketSupported {
665 m := new(newSessionTicketMsg)
668 state := sessionState{
670 cipherSuite: hs.suite.id,
671 masterSecret: hs.masterSecret,
672 certificates: hs.certsFromClient,
674 m.ticket, err = c.encryptTicket(&state)
679 hs.finishedHash.Write(m.marshal())
680 if _, err := c.writeRecord(recordTypeHandshake, m.marshal()); err != nil {
687 func (hs *serverHandshakeState) sendFinished(out []byte) error {
690 if _, err := c.writeRecord(recordTypeChangeCipherSpec, []byte{1}); err != nil {
694 finished := new(finishedMsg)
695 finished.verifyData = hs.finishedHash.serverSum(hs.masterSecret)
696 hs.finishedHash.Write(finished.marshal())
697 if _, err := c.writeRecord(recordTypeHandshake, finished.marshal()); err != nil {
701 c.cipherSuite = hs.suite.id
702 copy(out, finished.verifyData)
707 // processCertsFromClient takes a chain of client certificates either from a
708 // Certificates message or from a sessionState and verifies them. It returns
709 // the public key of the leaf certificate.
710 func (hs *serverHandshakeState) processCertsFromClient(certificates [][]byte) (crypto.PublicKey, error) {
713 hs.certsFromClient = certificates
714 certs := make([]*x509.Certificate, len(certificates))
716 for i, asn1Data := range certificates {
717 if certs[i], err = x509.ParseCertificate(asn1Data); err != nil {
718 c.sendAlert(alertBadCertificate)
719 return nil, errors.New("tls: failed to parse client certificate: " + err.Error())
723 if c.config.ClientAuth >= VerifyClientCertIfGiven && len(certs) > 0 {
724 opts := x509.VerifyOptions{
725 IsBoring: isBoringCertificate,
727 Roots: c.config.ClientCAs,
728 CurrentTime: c.config.time(),
729 Intermediates: x509.NewCertPool(),
730 KeyUsages: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth},
733 for _, cert := range certs[1:] {
734 opts.Intermediates.AddCert(cert)
737 chains, err := certs[0].Verify(opts)
739 c.sendAlert(alertBadCertificate)
740 return nil, errors.New("tls: failed to verify client's certificate: " + err.Error())
743 c.verifiedChains = chains
746 if c.config.VerifyPeerCertificate != nil {
747 if err := c.config.VerifyPeerCertificate(certificates, c.verifiedChains); err != nil {
748 c.sendAlert(alertBadCertificate)
757 var pub crypto.PublicKey
758 switch key := certs[0].PublicKey.(type) {
759 case *ecdsa.PublicKey, *rsa.PublicKey:
762 c.sendAlert(alertUnsupportedCertificate)
763 return nil, fmt.Errorf("tls: client's certificate contains an unsupported public key of type %T", certs[0].PublicKey)
765 c.peerCertificates = certs
769 // setCipherSuite sets a cipherSuite with the given id as the serverHandshakeState
770 // suite if that cipher suite is acceptable to use.
771 // It returns a bool indicating if the suite was set.
772 func (hs *serverHandshakeState) setCipherSuite(id uint16, supportedCipherSuites []uint16, version uint16) bool {
773 for _, supported := range supportedCipherSuites {
775 var candidate *cipherSuite
777 for _, s := range cipherSuites {
783 if candidate == nil {
786 // Don't select a ciphersuite which we can't
787 // support for this client.
788 if candidate.flags&suiteECDHE != 0 {
792 if candidate.flags&suiteECDSA != 0 {
796 } else if !hs.rsaSignOk {
799 } else if !hs.rsaDecryptOk {
802 if version < VersionTLS12 && candidate.flags&suiteTLS12 != 0 {
812 // suppVersArray is the backing array of ClientHelloInfo.SupportedVersions
813 var suppVersArray = [...]uint16{VersionTLS12, VersionTLS11, VersionTLS10, VersionSSL30}
815 func (hs *serverHandshakeState) clientHelloInfo() *ClientHelloInfo {
816 if hs.cachedClientHelloInfo != nil {
817 return hs.cachedClientHelloInfo
820 var supportedVersions []uint16
821 if hs.clientHello.vers > VersionTLS12 {
822 supportedVersions = suppVersArray[:]
823 } else if hs.clientHello.vers >= VersionSSL30 {
824 supportedVersions = suppVersArray[VersionTLS12-hs.clientHello.vers:]
827 hs.cachedClientHelloInfo = &ClientHelloInfo{
828 CipherSuites: hs.clientHello.cipherSuites,
829 ServerName: hs.clientHello.serverName,
830 SupportedCurves: hs.clientHello.supportedCurves,
831 SupportedPoints: hs.clientHello.supportedPoints,
832 SignatureSchemes: hs.clientHello.supportedSignatureAlgorithms,
833 SupportedProtos: hs.clientHello.alpnProtocols,
834 SupportedVersions: supportedVersions,
838 return hs.cachedClientHelloInfo