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.
20 // serverHandshakeState contains details of a server handshake in progress.
21 // It's discarded once the handshake has completed.
22 type serverHandshakeState struct {
24 clientHello *clientHelloMsg
31 sessionState *sessionState
32 finishedHash finishedHash
37 // serverHandshake performs a TLS handshake as a server.
38 func (c *Conn) serverHandshake() error {
39 // If this is the first server handshake, we generate a random key to
40 // encrypt the tickets with.
41 c.config.serverInitOnce.Do(func() { c.config.serverInit(nil) })
43 clientHello, err := c.readClientHello()
48 if c.vers == VersionTLS13 {
49 hs := serverHandshakeStateTLS13{
51 clientHello: clientHello,
56 hs := serverHandshakeState{
58 clientHello: clientHello,
63 func (hs *serverHandshakeState) handshake() error {
66 if err := hs.processClientHello(); err != nil {
70 // For an overview of TLS handshaking, see RFC 5246, Section 7.3.
72 if hs.checkForResumption() {
73 // The client has included a session ticket and so we do an abbreviated handshake.
74 if err := hs.doResumeHandshake(); err != nil {
77 if err := hs.establishKeys(); err != nil {
80 // ticketSupported is set in a resumption handshake if the
81 // ticket from the client was encrypted with an old session
82 // ticket key and thus a refreshed ticket should be sent.
83 if hs.hello.ticketSupported {
84 if err := hs.sendSessionTicket(); err != nil {
88 if err := hs.sendFinished(c.serverFinished[:]); err != nil {
91 if _, err := c.flush(); err != nil {
94 c.clientFinishedIsFirst = false
95 if err := hs.readFinished(nil); err != nil {
100 // The client didn't include a session ticket, or it wasn't
101 // valid so we do a full handshake.
102 if err := hs.pickCipherSuite(); err != nil {
105 if err := hs.doFullHandshake(); err != nil {
108 if err := hs.establishKeys(); err != nil {
111 if err := hs.readFinished(c.clientFinished[:]); err != nil {
114 c.clientFinishedIsFirst = true
116 if err := hs.sendSessionTicket(); err != nil {
119 if err := hs.sendFinished(nil); err != nil {
122 if _, err := c.flush(); err != nil {
127 c.ekm = ekmFromMasterSecret(c.vers, hs.suite, hs.masterSecret, hs.clientHello.random, hs.hello.random)
128 atomic.StoreUint32(&c.handshakeStatus, 1)
133 // readClientHello reads a ClientHello message and selects the protocol version.
134 func (c *Conn) readClientHello() (*clientHelloMsg, error) {
135 msg, err := c.readHandshake()
139 clientHello, ok := msg.(*clientHelloMsg)
141 c.sendAlert(alertUnexpectedMessage)
142 return nil, unexpectedMessageError(clientHello, msg)
145 if c.config.GetConfigForClient != nil {
146 chi := clientHelloInfo(c, clientHello)
147 if newConfig, err := c.config.GetConfigForClient(chi); err != nil {
148 c.sendAlert(alertInternalError)
150 } else if newConfig != nil {
151 newConfig.serverInitOnce.Do(func() { newConfig.serverInit(c.config) })
156 clientVersions := clientHello.supportedVersions
157 if len(clientHello.supportedVersions) == 0 {
158 clientVersions = supportedVersionsFromMax(clientHello.vers)
160 c.vers, ok = c.config.mutualVersion(false, clientVersions)
162 c.sendAlert(alertProtocolVersion)
163 return nil, fmt.Errorf("tls: client offered only unsupported versions: %x", clientVersions)
166 c.in.version = c.vers
167 c.out.version = c.vers
169 return clientHello, nil
172 func (hs *serverHandshakeState) processClientHello() error {
175 hs.hello = new(serverHelloMsg)
176 hs.hello.vers = c.vers
178 supportedCurve := false
179 preferredCurves := c.config.curvePreferences()
181 for _, curve := range hs.clientHello.supportedCurves {
182 for _, supported := range preferredCurves {
183 if supported == curve {
184 supportedCurve = true
190 supportedPointFormat := false
191 for _, pointFormat := range hs.clientHello.supportedPoints {
192 if pointFormat == pointFormatUncompressed {
193 supportedPointFormat = true
197 hs.ecdhOk = supportedCurve && supportedPointFormat
199 foundCompression := false
200 // We only support null compression, so check that the client offered it.
201 for _, compression := range hs.clientHello.compressionMethods {
202 if compression == compressionNone {
203 foundCompression = true
208 if !foundCompression {
209 c.sendAlert(alertHandshakeFailure)
210 return errors.New("tls: client does not support uncompressed connections")
213 hs.hello.random = make([]byte, 32)
214 serverRandom := hs.hello.random
215 // Downgrade protection canaries. See RFC 8446, Section 4.1.3.
216 maxVers := c.config.maxSupportedVersion(false)
217 if maxVers >= VersionTLS12 && c.vers < maxVers {
218 if c.vers == VersionTLS12 {
219 copy(serverRandom[24:], downgradeCanaryTLS12)
221 copy(serverRandom[24:], downgradeCanaryTLS11)
223 serverRandom = serverRandom[:24]
225 _, err := io.ReadFull(c.config.rand(), serverRandom)
227 c.sendAlert(alertInternalError)
231 if len(hs.clientHello.secureRenegotiation) != 0 {
232 c.sendAlert(alertHandshakeFailure)
233 return errors.New("tls: initial handshake had non-empty renegotiation extension")
236 hs.hello.secureRenegotiationSupported = hs.clientHello.secureRenegotiationSupported
237 hs.hello.compressionMethod = compressionNone
238 if len(hs.clientHello.serverName) > 0 {
239 c.serverName = hs.clientHello.serverName
242 if len(hs.clientHello.alpnProtocols) > 0 {
243 if selectedProto, fallback := mutualProtocol(hs.clientHello.alpnProtocols, c.config.NextProtos); !fallback {
244 hs.hello.alpnProtocol = selectedProto
245 c.clientProtocol = selectedProto
248 // Although sending an empty NPN extension is reasonable, Firefox has
249 // had a bug around this. Best to send nothing at all if
250 // c.config.NextProtos is empty. See
251 // https://golang.org/issue/5445.
252 if hs.clientHello.nextProtoNeg && len(c.config.NextProtos) > 0 {
253 hs.hello.nextProtoNeg = true
254 hs.hello.nextProtos = c.config.NextProtos
258 hs.cert, err = c.config.getCertificate(clientHelloInfo(c, hs.clientHello))
260 c.sendAlert(alertInternalError)
263 if hs.clientHello.scts {
264 hs.hello.scts = hs.cert.SignedCertificateTimestamps
267 if priv, ok := hs.cert.PrivateKey.(crypto.Signer); ok {
268 switch priv.Public().(type) {
269 case *ecdsa.PublicKey:
271 case ed25519.PublicKey:
276 c.sendAlert(alertInternalError)
277 return fmt.Errorf("tls: unsupported signing key type (%T)", priv.Public())
280 if priv, ok := hs.cert.PrivateKey.(crypto.Decrypter); ok {
281 switch priv.Public().(type) {
283 hs.rsaDecryptOk = true
285 c.sendAlert(alertInternalError)
286 return fmt.Errorf("tls: unsupported decryption key type (%T)", priv.Public())
293 func (hs *serverHandshakeState) pickCipherSuite() error {
296 var preferenceList, supportedList []uint16
297 if c.config.PreferServerCipherSuites {
298 preferenceList = c.config.cipherSuites()
299 supportedList = hs.clientHello.cipherSuites
301 preferenceList = hs.clientHello.cipherSuites
302 supportedList = c.config.cipherSuites()
305 for _, id := range preferenceList {
306 if hs.setCipherSuite(id, supportedList, c.vers) {
312 c.sendAlert(alertHandshakeFailure)
313 return errors.New("tls: no cipher suite supported by both client and server")
316 for _, id := range hs.clientHello.cipherSuites {
317 if id == TLS_FALLBACK_SCSV {
318 // The client is doing a fallback connection. See RFC 7507.
319 if hs.clientHello.vers < c.config.maxSupportedVersion(false) {
320 c.sendAlert(alertInappropriateFallback)
321 return errors.New("tls: client using inappropriate protocol fallback")
330 // checkForResumption reports whether we should perform resumption on this connection.
331 func (hs *serverHandshakeState) checkForResumption() bool {
334 if c.config.SessionTicketsDisabled {
338 plaintext, usedOldKey := c.decryptTicket(hs.clientHello.sessionTicket)
339 if plaintext == nil {
342 hs.sessionState = &sessionState{usedOldKey: usedOldKey}
343 ok := hs.sessionState.unmarshal(plaintext)
348 // Never resume a session for a different TLS version.
349 if c.vers != hs.sessionState.vers {
353 cipherSuiteOk := false
354 // Check that the client is still offering the ciphersuite in the session.
355 for _, id := range hs.clientHello.cipherSuites {
356 if id == hs.sessionState.cipherSuite {
365 // Check that we also support the ciphersuite from the session.
366 if !hs.setCipherSuite(hs.sessionState.cipherSuite, c.config.cipherSuites(), hs.sessionState.vers) {
370 sessionHasClientCerts := len(hs.sessionState.certificates) != 0
371 needClientCerts := requiresClientCert(c.config.ClientAuth)
372 if needClientCerts && !sessionHasClientCerts {
375 if sessionHasClientCerts && c.config.ClientAuth == NoClientCert {
382 func (hs *serverHandshakeState) doResumeHandshake() error {
385 hs.hello.cipherSuite = hs.suite.id
386 // We echo the client's session ID in the ServerHello to let it know
387 // that we're doing a resumption.
388 hs.hello.sessionId = hs.clientHello.sessionId
389 hs.hello.ticketSupported = hs.sessionState.usedOldKey
390 hs.finishedHash = newFinishedHash(c.vers, hs.suite)
391 hs.finishedHash.discardHandshakeBuffer()
392 hs.finishedHash.Write(hs.clientHello.marshal())
393 hs.finishedHash.Write(hs.hello.marshal())
394 if _, err := c.writeRecord(recordTypeHandshake, hs.hello.marshal()); err != nil {
398 if err := c.processCertsFromClient(Certificate{
399 Certificate: hs.sessionState.certificates,
404 hs.masterSecret = hs.sessionState.masterSecret
409 func (hs *serverHandshakeState) doFullHandshake() error {
412 if hs.clientHello.ocspStapling && len(hs.cert.OCSPStaple) > 0 {
413 hs.hello.ocspStapling = true
416 hs.hello.ticketSupported = hs.clientHello.ticketSupported && !c.config.SessionTicketsDisabled
417 hs.hello.cipherSuite = hs.suite.id
419 hs.finishedHash = newFinishedHash(hs.c.vers, hs.suite)
420 if c.config.ClientAuth == NoClientCert {
421 // No need to keep a full record of the handshake if client
422 // certificates won't be used.
423 hs.finishedHash.discardHandshakeBuffer()
425 hs.finishedHash.Write(hs.clientHello.marshal())
426 hs.finishedHash.Write(hs.hello.marshal())
427 if _, err := c.writeRecord(recordTypeHandshake, hs.hello.marshal()); err != nil {
431 certMsg := new(certificateMsg)
432 certMsg.certificates = hs.cert.Certificate
433 hs.finishedHash.Write(certMsg.marshal())
434 if _, err := c.writeRecord(recordTypeHandshake, certMsg.marshal()); err != nil {
438 if hs.hello.ocspStapling {
439 certStatus := new(certificateStatusMsg)
440 certStatus.response = hs.cert.OCSPStaple
441 hs.finishedHash.Write(certStatus.marshal())
442 if _, err := c.writeRecord(recordTypeHandshake, certStatus.marshal()); err != nil {
447 keyAgreement := hs.suite.ka(c.vers)
448 skx, err := keyAgreement.generateServerKeyExchange(c.config, hs.cert, hs.clientHello, hs.hello)
450 c.sendAlert(alertHandshakeFailure)
454 hs.finishedHash.Write(skx.marshal())
455 if _, err := c.writeRecord(recordTypeHandshake, skx.marshal()); err != nil {
460 var certReq *certificateRequestMsg
461 if c.config.ClientAuth >= RequestClientCert {
462 // Request a client certificate
463 certReq = new(certificateRequestMsg)
464 certReq.certificateTypes = []byte{
465 byte(certTypeRSASign),
466 byte(certTypeECDSASign),
468 if c.vers >= VersionTLS12 {
469 certReq.hasSignatureAlgorithm = true
470 certReq.supportedSignatureAlgorithms = supportedSignatureAlgorithmsTLS12
473 // An empty list of certificateAuthorities signals to
474 // the client that it may send any certificate in response
475 // to our request. When we know the CAs we trust, then
476 // we can send them down, so that the client can choose
477 // an appropriate certificate to give to us.
478 if c.config.ClientCAs != nil {
479 certReq.certificateAuthorities = c.config.ClientCAs.Subjects()
481 hs.finishedHash.Write(certReq.marshal())
482 if _, err := c.writeRecord(recordTypeHandshake, certReq.marshal()); err != nil {
487 helloDone := new(serverHelloDoneMsg)
488 hs.finishedHash.Write(helloDone.marshal())
489 if _, err := c.writeRecord(recordTypeHandshake, helloDone.marshal()); err != nil {
493 if _, err := c.flush(); err != nil {
497 var pub crypto.PublicKey // public key for client auth, if any
499 msg, err := c.readHandshake()
504 // If we requested a client certificate, then the client must send a
505 // certificate message, even if it's empty.
506 if c.config.ClientAuth >= RequestClientCert {
507 certMsg, ok := msg.(*certificateMsg)
509 c.sendAlert(alertUnexpectedMessage)
510 return unexpectedMessageError(certMsg, msg)
512 hs.finishedHash.Write(certMsg.marshal())
514 if err := c.processCertsFromClient(Certificate{
515 Certificate: certMsg.certificates,
519 if len(certMsg.certificates) != 0 {
520 pub = c.peerCertificates[0].PublicKey
523 msg, err = c.readHandshake()
529 // Get client key exchange
530 ckx, ok := msg.(*clientKeyExchangeMsg)
532 c.sendAlert(alertUnexpectedMessage)
533 return unexpectedMessageError(ckx, msg)
535 hs.finishedHash.Write(ckx.marshal())
537 preMasterSecret, err := keyAgreement.processClientKeyExchange(c.config, hs.cert, ckx, c.vers)
539 c.sendAlert(alertHandshakeFailure)
542 hs.masterSecret = masterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret, hs.clientHello.random, hs.hello.random)
543 if err := c.config.writeKeyLog(keyLogLabelTLS12, hs.clientHello.random, hs.masterSecret); err != nil {
544 c.sendAlert(alertInternalError)
548 // If we received a client cert in response to our certificate request message,
549 // the client will send us a certificateVerifyMsg immediately after the
550 // clientKeyExchangeMsg. This message is a digest of all preceding
551 // handshake-layer messages that is signed using the private key corresponding
552 // to the client's certificate. This allows us to verify that the client is in
553 // possession of the private key of the certificate.
554 if len(c.peerCertificates) > 0 {
555 msg, err = c.readHandshake()
559 certVerify, ok := msg.(*certificateVerifyMsg)
561 c.sendAlert(alertUnexpectedMessage)
562 return unexpectedMessageError(certVerify, msg)
565 // Determine the signature type.
566 _, sigType, hashFunc, err := pickSignatureAlgorithm(pub, []SignatureScheme{certVerify.signatureAlgorithm}, certReq.supportedSignatureAlgorithms, c.vers)
568 c.sendAlert(alertIllegalParameter)
572 signed, err := hs.finishedHash.hashForClientCertificate(sigType, hashFunc, hs.masterSecret)
574 err = verifyHandshakeSignature(sigType, pub, hashFunc, signed, certVerify.signature)
577 c.sendAlert(alertBadCertificate)
578 return errors.New("tls: could not validate signature of connection nonces: " + err.Error())
581 hs.finishedHash.Write(certVerify.marshal())
584 hs.finishedHash.discardHandshakeBuffer()
589 func (hs *serverHandshakeState) establishKeys() error {
592 clientMAC, serverMAC, clientKey, serverKey, clientIV, serverIV :=
593 keysFromMasterSecret(c.vers, hs.suite, hs.masterSecret, hs.clientHello.random, hs.hello.random, hs.suite.macLen, hs.suite.keyLen, hs.suite.ivLen)
595 var clientCipher, serverCipher interface{}
596 var clientHash, serverHash macFunction
598 if hs.suite.aead == nil {
599 clientCipher = hs.suite.cipher(clientKey, clientIV, true /* for reading */)
600 clientHash = hs.suite.mac(c.vers, clientMAC)
601 serverCipher = hs.suite.cipher(serverKey, serverIV, false /* not for reading */)
602 serverHash = hs.suite.mac(c.vers, serverMAC)
604 clientCipher = hs.suite.aead(clientKey, clientIV)
605 serverCipher = hs.suite.aead(serverKey, serverIV)
608 c.in.prepareCipherSpec(c.vers, clientCipher, clientHash)
609 c.out.prepareCipherSpec(c.vers, serverCipher, serverHash)
614 func (hs *serverHandshakeState) readFinished(out []byte) error {
617 if err := c.readChangeCipherSpec(); err != nil {
621 if hs.hello.nextProtoNeg {
622 msg, err := c.readHandshake()
626 nextProto, ok := msg.(*nextProtoMsg)
628 c.sendAlert(alertUnexpectedMessage)
629 return unexpectedMessageError(nextProto, msg)
631 hs.finishedHash.Write(nextProto.marshal())
632 c.clientProtocol = nextProto.proto
635 msg, err := c.readHandshake()
639 clientFinished, ok := msg.(*finishedMsg)
641 c.sendAlert(alertUnexpectedMessage)
642 return unexpectedMessageError(clientFinished, msg)
645 verify := hs.finishedHash.clientSum(hs.masterSecret)
646 if len(verify) != len(clientFinished.verifyData) ||
647 subtle.ConstantTimeCompare(verify, clientFinished.verifyData) != 1 {
648 c.sendAlert(alertHandshakeFailure)
649 return errors.New("tls: client's Finished message is incorrect")
652 hs.finishedHash.Write(clientFinished.marshal())
657 func (hs *serverHandshakeState) sendSessionTicket() error {
658 if !hs.hello.ticketSupported {
663 m := new(newSessionTicketMsg)
665 var certsFromClient [][]byte
666 for _, cert := range c.peerCertificates {
667 certsFromClient = append(certsFromClient, cert.Raw)
669 state := sessionState{
671 cipherSuite: hs.suite.id,
672 masterSecret: hs.masterSecret,
673 certificates: certsFromClient,
676 m.ticket, err = c.encryptTicket(state.marshal())
681 hs.finishedHash.Write(m.marshal())
682 if _, err := c.writeRecord(recordTypeHandshake, m.marshal()); err != nil {
689 func (hs *serverHandshakeState) sendFinished(out []byte) error {
692 if _, err := c.writeRecord(recordTypeChangeCipherSpec, []byte{1}); err != nil {
696 finished := new(finishedMsg)
697 finished.verifyData = hs.finishedHash.serverSum(hs.masterSecret)
698 hs.finishedHash.Write(finished.marshal())
699 if _, err := c.writeRecord(recordTypeHandshake, finished.marshal()); err != nil {
703 c.cipherSuite = hs.suite.id
704 copy(out, finished.verifyData)
709 // processCertsFromClient takes a chain of client certificates either from a
710 // Certificates message or from a sessionState and verifies them. It returns
711 // the public key of the leaf certificate.
712 func (c *Conn) processCertsFromClient(certificate Certificate) error {
713 certificates := certificate.Certificate
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 errors.New("tls: failed to parse client certificate: " + err.Error())
723 if len(certs) == 0 && requiresClientCert(c.config.ClientAuth) {
724 c.sendAlert(alertBadCertificate)
725 return errors.New("tls: client didn't provide a certificate")
728 if c.config.ClientAuth >= VerifyClientCertIfGiven && len(certs) > 0 {
729 opts := x509.VerifyOptions{
730 Roots: c.config.ClientCAs,
731 CurrentTime: c.config.time(),
732 Intermediates: x509.NewCertPool(),
733 KeyUsages: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth},
736 for _, cert := range certs[1:] {
737 opts.Intermediates.AddCert(cert)
740 chains, err := certs[0].Verify(opts)
742 c.sendAlert(alertBadCertificate)
743 return errors.New("tls: failed to verify client's certificate: " + err.Error())
746 c.verifiedChains = chains
749 if c.config.VerifyPeerCertificate != nil {
750 if err := c.config.VerifyPeerCertificate(certificates, c.verifiedChains); err != nil {
751 c.sendAlert(alertBadCertificate)
760 switch certs[0].PublicKey.(type) {
761 case *ecdsa.PublicKey, *rsa.PublicKey, ed25519.PublicKey:
763 c.sendAlert(alertUnsupportedCertificate)
764 return fmt.Errorf("tls: client's certificate contains an unsupported public key of type %T", certs[0].PublicKey)
767 c.peerCertificates = certs
768 c.ocspResponse = certificate.OCSPStaple
769 c.scts = certificate.SignedCertificateTimestamps
773 // setCipherSuite sets a cipherSuite with the given id as the serverHandshakeState
774 // suite if that cipher suite is acceptable to use.
775 // It returns a bool indicating if the suite was set.
776 func (hs *serverHandshakeState) setCipherSuite(id uint16, supportedCipherSuites []uint16, version uint16) bool {
777 for _, supported := range supportedCipherSuites {
781 candidate := cipherSuiteByID(id)
782 if candidate == nil {
785 // Don't select a ciphersuite which we can't
786 // support for this client.
787 if candidate.flags&suiteECDHE != 0 {
791 if candidate.flags&suiteECSign != 0 {
795 } else if !hs.rsaSignOk {
798 } else if !hs.rsaDecryptOk {
801 if version < VersionTLS12 && candidate.flags&suiteTLS12 != 0 {
810 func clientHelloInfo(c *Conn, clientHello *clientHelloMsg) *ClientHelloInfo {
811 supportedVersions := clientHello.supportedVersions
812 if len(clientHello.supportedVersions) == 0 {
813 supportedVersions = supportedVersionsFromMax(clientHello.vers)
816 return &ClientHelloInfo{
817 CipherSuites: clientHello.cipherSuites,
818 ServerName: clientHello.serverName,
819 SupportedCurves: clientHello.supportedCurves,
820 SupportedPoints: clientHello.supportedPoints,
821 SignatureSchemes: clientHello.supportedSignatureAlgorithms,
822 SupportedProtos: clientHello.alpnProtocols,
823 SupportedVersions: supportedVersions,