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
36 // serverHandshake performs a TLS handshake as a server.
37 func (c *Conn) serverHandshake() error {
38 // If this is the first server handshake, we generate a random key to
39 // encrypt the tickets with.
40 c.config.serverInitOnce.Do(func() { c.config.serverInit(nil) })
42 clientHello, err := c.readClientHello()
47 if c.vers == VersionTLS13 {
48 hs := serverHandshakeStateTLS13{
50 clientHello: clientHello,
55 hs := serverHandshakeState{
57 clientHello: clientHello,
62 func (hs *serverHandshakeState) handshake() error {
65 if err := hs.processClientHello(); err != nil {
69 // For an overview of TLS handshaking, see RFC 5246, Section 7.3.
71 if hs.checkForResumption() {
72 // The client has included a session ticket and so we do an abbreviated handshake.
73 if err := hs.doResumeHandshake(); err != nil {
76 if err := hs.establishKeys(); err != nil {
79 // ticketSupported is set in a resumption handshake if the
80 // ticket from the client was encrypted with an old session
81 // ticket key and thus a refreshed ticket should be sent.
82 if hs.hello.ticketSupported {
83 if err := hs.sendSessionTicket(); err != nil {
87 if err := hs.sendFinished(c.serverFinished[:]); err != nil {
90 if _, err := c.flush(); err != nil {
93 c.clientFinishedIsFirst = false
94 if err := hs.readFinished(nil); err != nil {
99 // The client didn't include a session ticket, or it wasn't
100 // valid so we do a full handshake.
101 if err := hs.pickCipherSuite(); err != nil {
104 if err := hs.doFullHandshake(); err != nil {
107 if err := hs.establishKeys(); err != nil {
110 if err := hs.readFinished(c.clientFinished[:]); err != nil {
113 c.clientFinishedIsFirst = true
115 if err := hs.sendSessionTicket(); err != nil {
118 if err := hs.sendFinished(nil); err != nil {
121 if _, err := c.flush(); err != nil {
126 c.ekm = ekmFromMasterSecret(c.vers, hs.suite, hs.masterSecret, hs.clientHello.random, hs.hello.random)
127 atomic.StoreUint32(&c.handshakeStatus, 1)
132 // readClientHello reads a ClientHello message and selects the protocol version.
133 func (c *Conn) readClientHello() (*clientHelloMsg, error) {
134 msg, err := c.readHandshake()
138 clientHello, ok := msg.(*clientHelloMsg)
140 c.sendAlert(alertUnexpectedMessage)
141 return nil, unexpectedMessageError(clientHello, msg)
144 if c.config.GetConfigForClient != nil {
145 chi := clientHelloInfo(c, clientHello)
146 if newConfig, err := c.config.GetConfigForClient(chi); err != nil {
147 c.sendAlert(alertInternalError)
149 } else if newConfig != nil {
150 newConfig.serverInitOnce.Do(func() { newConfig.serverInit(c.config) })
155 clientVersions := clientHello.supportedVersions
156 if len(clientHello.supportedVersions) == 0 {
157 clientVersions = supportedVersionsFromMax(clientHello.vers)
159 c.vers, ok = c.config.mutualVersion(false, clientVersions)
161 c.sendAlert(alertProtocolVersion)
162 return nil, fmt.Errorf("tls: client offered only unsupported versions: %x", clientVersions)
165 c.in.version = c.vers
166 c.out.version = c.vers
168 return clientHello, nil
171 func (hs *serverHandshakeState) processClientHello() error {
174 hs.hello = new(serverHelloMsg)
175 hs.hello.vers = c.vers
177 supportedCurve := false
178 preferredCurves := c.config.curvePreferences()
180 for _, curve := range hs.clientHello.supportedCurves {
181 for _, supported := range preferredCurves {
182 if supported == curve {
183 supportedCurve = true
189 supportedPointFormat := false
190 for _, pointFormat := range hs.clientHello.supportedPoints {
191 if pointFormat == pointFormatUncompressed {
192 supportedPointFormat = true
196 hs.ellipticOk = supportedCurve && supportedPointFormat
198 foundCompression := false
199 // We only support null compression, so check that the client offered it.
200 for _, compression := range hs.clientHello.compressionMethods {
201 if compression == compressionNone {
202 foundCompression = true
207 if !foundCompression {
208 c.sendAlert(alertHandshakeFailure)
209 return errors.New("tls: client does not support uncompressed connections")
212 hs.hello.random = make([]byte, 32)
213 serverRandom := hs.hello.random
214 // Downgrade protection canaries. See RFC 8446, Section 4.1.3.
215 maxVers := c.config.maxSupportedVersion(false)
216 if maxVers >= VersionTLS12 && c.vers < maxVers {
217 if c.vers == VersionTLS12 {
218 copy(serverRandom[24:], downgradeCanaryTLS12)
220 copy(serverRandom[24:], downgradeCanaryTLS11)
222 serverRandom = serverRandom[:24]
224 _, err := io.ReadFull(c.config.rand(), serverRandom)
226 c.sendAlert(alertInternalError)
230 if len(hs.clientHello.secureRenegotiation) != 0 {
231 c.sendAlert(alertHandshakeFailure)
232 return errors.New("tls: initial handshake had non-empty renegotiation extension")
235 hs.hello.secureRenegotiationSupported = hs.clientHello.secureRenegotiationSupported
236 hs.hello.compressionMethod = compressionNone
237 if len(hs.clientHello.serverName) > 0 {
238 c.serverName = hs.clientHello.serverName
241 if len(hs.clientHello.alpnProtocols) > 0 {
242 if selectedProto, fallback := mutualProtocol(hs.clientHello.alpnProtocols, c.config.NextProtos); !fallback {
243 hs.hello.alpnProtocol = selectedProto
244 c.clientProtocol = selectedProto
247 // Although sending an empty NPN extension is reasonable, Firefox has
248 // had a bug around this. Best to send nothing at all if
249 // c.config.NextProtos is empty. See
250 // https://golang.org/issue/5445.
251 if hs.clientHello.nextProtoNeg && len(c.config.NextProtos) > 0 {
252 hs.hello.nextProtoNeg = true
253 hs.hello.nextProtos = c.config.NextProtos
257 hs.cert, err = c.config.getCertificate(clientHelloInfo(c, hs.clientHello))
259 c.sendAlert(alertInternalError)
262 if hs.clientHello.scts {
263 hs.hello.scts = hs.cert.SignedCertificateTimestamps
266 if priv, ok := hs.cert.PrivateKey.(crypto.Signer); ok {
267 switch priv.Public().(type) {
268 case *ecdsa.PublicKey:
273 c.sendAlert(alertInternalError)
274 return fmt.Errorf("tls: unsupported signing key type (%T)", priv.Public())
277 if priv, ok := hs.cert.PrivateKey.(crypto.Decrypter); ok {
278 switch priv.Public().(type) {
280 hs.rsaDecryptOk = true
282 c.sendAlert(alertInternalError)
283 return fmt.Errorf("tls: unsupported decryption key type (%T)", priv.Public())
290 func (hs *serverHandshakeState) pickCipherSuite() error {
293 var preferenceList, supportedList []uint16
294 if c.config.PreferServerCipherSuites {
295 preferenceList = c.config.cipherSuites()
296 supportedList = hs.clientHello.cipherSuites
298 preferenceList = hs.clientHello.cipherSuites
299 supportedList = c.config.cipherSuites()
302 for _, id := range preferenceList {
303 if hs.setCipherSuite(id, supportedList, c.vers) {
309 c.sendAlert(alertHandshakeFailure)
310 return errors.New("tls: no cipher suite supported by both client and server")
313 for _, id := range hs.clientHello.cipherSuites {
314 if id == TLS_FALLBACK_SCSV {
315 // The client is doing a fallback connection. See RFC 7507.
316 if hs.clientHello.vers < c.config.maxSupportedVersion(false) {
317 c.sendAlert(alertInappropriateFallback)
318 return errors.New("tls: client using inappropriate protocol fallback")
327 // checkForResumption reports whether we should perform resumption on this connection.
328 func (hs *serverHandshakeState) checkForResumption() bool {
331 if c.config.SessionTicketsDisabled {
335 plaintext, usedOldKey := c.decryptTicket(hs.clientHello.sessionTicket)
336 if plaintext == nil {
339 hs.sessionState = &sessionState{usedOldKey: usedOldKey}
340 ok := hs.sessionState.unmarshal(plaintext)
345 // Never resume a session for a different TLS version.
346 if c.vers != hs.sessionState.vers {
350 cipherSuiteOk := false
351 // Check that the client is still offering the ciphersuite in the session.
352 for _, id := range hs.clientHello.cipherSuites {
353 if id == hs.sessionState.cipherSuite {
362 // Check that we also support the ciphersuite from the session.
363 if !hs.setCipherSuite(hs.sessionState.cipherSuite, c.config.cipherSuites(), hs.sessionState.vers) {
367 sessionHasClientCerts := len(hs.sessionState.certificates) != 0
368 needClientCerts := requiresClientCert(c.config.ClientAuth)
369 if needClientCerts && !sessionHasClientCerts {
372 if sessionHasClientCerts && c.config.ClientAuth == NoClientCert {
379 func (hs *serverHandshakeState) doResumeHandshake() error {
382 hs.hello.cipherSuite = hs.suite.id
383 // We echo the client's session ID in the ServerHello to let it know
384 // that we're doing a resumption.
385 hs.hello.sessionId = hs.clientHello.sessionId
386 hs.hello.ticketSupported = hs.sessionState.usedOldKey
387 hs.finishedHash = newFinishedHash(c.vers, hs.suite)
388 hs.finishedHash.discardHandshakeBuffer()
389 hs.finishedHash.Write(hs.clientHello.marshal())
390 hs.finishedHash.Write(hs.hello.marshal())
391 if _, err := c.writeRecord(recordTypeHandshake, hs.hello.marshal()); err != nil {
395 if err := c.processCertsFromClient(Certificate{
396 Certificate: hs.sessionState.certificates,
401 hs.masterSecret = hs.sessionState.masterSecret
406 func (hs *serverHandshakeState) doFullHandshake() error {
409 if hs.clientHello.ocspStapling && len(hs.cert.OCSPStaple) > 0 {
410 hs.hello.ocspStapling = true
413 hs.hello.ticketSupported = hs.clientHello.ticketSupported && !c.config.SessionTicketsDisabled
414 hs.hello.cipherSuite = hs.suite.id
416 hs.finishedHash = newFinishedHash(hs.c.vers, hs.suite)
417 if c.config.ClientAuth == NoClientCert {
418 // No need to keep a full record of the handshake if client
419 // certificates won't be used.
420 hs.finishedHash.discardHandshakeBuffer()
422 hs.finishedHash.Write(hs.clientHello.marshal())
423 hs.finishedHash.Write(hs.hello.marshal())
424 if _, err := c.writeRecord(recordTypeHandshake, hs.hello.marshal()); err != nil {
428 certMsg := new(certificateMsg)
429 certMsg.certificates = hs.cert.Certificate
430 hs.finishedHash.Write(certMsg.marshal())
431 if _, err := c.writeRecord(recordTypeHandshake, certMsg.marshal()); err != nil {
435 if hs.hello.ocspStapling {
436 certStatus := new(certificateStatusMsg)
437 certStatus.response = hs.cert.OCSPStaple
438 hs.finishedHash.Write(certStatus.marshal())
439 if _, err := c.writeRecord(recordTypeHandshake, certStatus.marshal()); err != nil {
444 keyAgreement := hs.suite.ka(c.vers)
445 skx, err := keyAgreement.generateServerKeyExchange(c.config, hs.cert, hs.clientHello, hs.hello)
447 c.sendAlert(alertHandshakeFailure)
451 hs.finishedHash.Write(skx.marshal())
452 if _, err := c.writeRecord(recordTypeHandshake, skx.marshal()); err != nil {
457 if c.config.ClientAuth >= RequestClientCert {
458 // Request a client certificate
459 certReq := new(certificateRequestMsg)
460 certReq.certificateTypes = []byte{
461 byte(certTypeRSASign),
462 byte(certTypeECDSASign),
464 if c.vers >= VersionTLS12 {
465 certReq.hasSignatureAlgorithm = true
466 certReq.supportedSignatureAlgorithms = supportedSignatureAlgorithms()
469 // An empty list of certificateAuthorities signals to
470 // the client that it may send any certificate in response
471 // to our request. When we know the CAs we trust, then
472 // we can send them down, so that the client can choose
473 // an appropriate certificate to give to us.
474 if c.config.ClientCAs != nil {
475 certReq.certificateAuthorities = c.config.ClientCAs.Subjects()
477 hs.finishedHash.Write(certReq.marshal())
478 if _, err := c.writeRecord(recordTypeHandshake, certReq.marshal()); err != nil {
483 helloDone := new(serverHelloDoneMsg)
484 hs.finishedHash.Write(helloDone.marshal())
485 if _, err := c.writeRecord(recordTypeHandshake, helloDone.marshal()); err != nil {
489 if _, err := c.flush(); err != nil {
493 var pub crypto.PublicKey // public key for client auth, if any
495 msg, err := c.readHandshake()
500 // If we requested a client certificate, then the client must send a
501 // certificate message, even if it's empty.
502 if c.config.ClientAuth >= RequestClientCert {
503 certMsg, ok := msg.(*certificateMsg)
505 c.sendAlert(alertUnexpectedMessage)
506 return unexpectedMessageError(certMsg, msg)
508 hs.finishedHash.Write(certMsg.marshal())
510 if err := c.processCertsFromClient(Certificate{
511 Certificate: certMsg.certificates,
515 if len(certMsg.certificates) != 0 {
516 pub = c.peerCertificates[0].PublicKey
519 msg, err = c.readHandshake()
525 // Get client key exchange
526 ckx, ok := msg.(*clientKeyExchangeMsg)
528 c.sendAlert(alertUnexpectedMessage)
529 return unexpectedMessageError(ckx, msg)
531 hs.finishedHash.Write(ckx.marshal())
533 preMasterSecret, err := keyAgreement.processClientKeyExchange(c.config, hs.cert, ckx, c.vers)
535 c.sendAlert(alertHandshakeFailure)
538 hs.masterSecret = masterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret, hs.clientHello.random, hs.hello.random)
539 if err := c.config.writeKeyLog(keyLogLabelTLS12, hs.clientHello.random, hs.masterSecret); err != nil {
540 c.sendAlert(alertInternalError)
544 // If we received a client cert in response to our certificate request message,
545 // the client will send us a certificateVerifyMsg immediately after the
546 // clientKeyExchangeMsg. This message is a digest of all preceding
547 // handshake-layer messages that is signed using the private key corresponding
548 // to the client's certificate. This allows us to verify that the client is in
549 // possession of the private key of the certificate.
550 if len(c.peerCertificates) > 0 {
551 msg, err = c.readHandshake()
555 certVerify, ok := msg.(*certificateVerifyMsg)
557 c.sendAlert(alertUnexpectedMessage)
558 return unexpectedMessageError(certVerify, msg)
561 // Determine the signature type.
562 _, sigType, hashFunc, err := pickSignatureAlgorithm(pub, []SignatureScheme{certVerify.signatureAlgorithm}, supportedSignatureAlgorithms(), c.vers)
564 c.sendAlert(alertIllegalParameter)
569 if digest, err = hs.finishedHash.hashForClientCertificate(sigType, hashFunc, hs.masterSecret); err == nil {
570 err = verifyHandshakeSignature(sigType, pub, hashFunc, digest, certVerify.signature)
573 c.sendAlert(alertBadCertificate)
574 return errors.New("tls: could not validate signature of connection nonces: " + err.Error())
577 hs.finishedHash.Write(certVerify.marshal())
580 hs.finishedHash.discardHandshakeBuffer()
585 func (hs *serverHandshakeState) establishKeys() error {
588 clientMAC, serverMAC, clientKey, serverKey, clientIV, serverIV :=
589 keysFromMasterSecret(c.vers, hs.suite, hs.masterSecret, hs.clientHello.random, hs.hello.random, hs.suite.macLen, hs.suite.keyLen, hs.suite.ivLen)
591 var clientCipher, serverCipher interface{}
592 var clientHash, serverHash macFunction
594 if hs.suite.aead == nil {
595 clientCipher = hs.suite.cipher(clientKey, clientIV, true /* for reading */)
596 clientHash = hs.suite.mac(c.vers, clientMAC)
597 serverCipher = hs.suite.cipher(serverKey, serverIV, false /* not for reading */)
598 serverHash = hs.suite.mac(c.vers, serverMAC)
600 clientCipher = hs.suite.aead(clientKey, clientIV)
601 serverCipher = hs.suite.aead(serverKey, serverIV)
604 c.in.prepareCipherSpec(c.vers, clientCipher, clientHash)
605 c.out.prepareCipherSpec(c.vers, serverCipher, serverHash)
610 func (hs *serverHandshakeState) readFinished(out []byte) error {
613 if err := c.readChangeCipherSpec(); err != nil {
617 if hs.hello.nextProtoNeg {
618 msg, err := c.readHandshake()
622 nextProto, ok := msg.(*nextProtoMsg)
624 c.sendAlert(alertUnexpectedMessage)
625 return unexpectedMessageError(nextProto, msg)
627 hs.finishedHash.Write(nextProto.marshal())
628 c.clientProtocol = nextProto.proto
631 msg, err := c.readHandshake()
635 clientFinished, ok := msg.(*finishedMsg)
637 c.sendAlert(alertUnexpectedMessage)
638 return unexpectedMessageError(clientFinished, msg)
641 verify := hs.finishedHash.clientSum(hs.masterSecret)
642 if len(verify) != len(clientFinished.verifyData) ||
643 subtle.ConstantTimeCompare(verify, clientFinished.verifyData) != 1 {
644 c.sendAlert(alertHandshakeFailure)
645 return errors.New("tls: client's Finished message is incorrect")
648 hs.finishedHash.Write(clientFinished.marshal())
653 func (hs *serverHandshakeState) sendSessionTicket() error {
654 if !hs.hello.ticketSupported {
659 m := new(newSessionTicketMsg)
661 var certsFromClient [][]byte
662 for _, cert := range c.peerCertificates {
663 certsFromClient = append(certsFromClient, cert.Raw)
665 state := sessionState{
667 cipherSuite: hs.suite.id,
668 masterSecret: hs.masterSecret,
669 certificates: certsFromClient,
672 m.ticket, err = c.encryptTicket(state.marshal())
677 hs.finishedHash.Write(m.marshal())
678 if _, err := c.writeRecord(recordTypeHandshake, m.marshal()); err != nil {
685 func (hs *serverHandshakeState) sendFinished(out []byte) error {
688 if _, err := c.writeRecord(recordTypeChangeCipherSpec, []byte{1}); err != nil {
692 finished := new(finishedMsg)
693 finished.verifyData = hs.finishedHash.serverSum(hs.masterSecret)
694 hs.finishedHash.Write(finished.marshal())
695 if _, err := c.writeRecord(recordTypeHandshake, finished.marshal()); err != nil {
699 c.cipherSuite = hs.suite.id
700 copy(out, finished.verifyData)
705 // processCertsFromClient takes a chain of client certificates either from a
706 // Certificates message or from a sessionState and verifies them. It returns
707 // the public key of the leaf certificate.
708 func (c *Conn) processCertsFromClient(certificate Certificate) error {
709 certificates := certificate.Certificate
710 certs := make([]*x509.Certificate, len(certificates))
712 for i, asn1Data := range certificates {
713 if certs[i], err = x509.ParseCertificate(asn1Data); err != nil {
714 c.sendAlert(alertBadCertificate)
715 return errors.New("tls: failed to parse client certificate: " + err.Error())
719 if len(certs) == 0 && requiresClientCert(c.config.ClientAuth) {
720 c.sendAlert(alertBadCertificate)
721 return errors.New("tls: client didn't provide a certificate")
724 if c.config.ClientAuth >= VerifyClientCertIfGiven && len(certs) > 0 {
725 opts := x509.VerifyOptions{
726 IsBoring: isBoringCertificate,
728 Roots: c.config.ClientCAs,
729 CurrentTime: c.config.time(),
730 Intermediates: x509.NewCertPool(),
731 KeyUsages: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth},
734 for _, cert := range certs[1:] {
735 opts.Intermediates.AddCert(cert)
738 chains, err := certs[0].Verify(opts)
740 c.sendAlert(alertBadCertificate)
741 return errors.New("tls: failed to verify client's certificate: " + err.Error())
744 c.verifiedChains = chains
747 if c.config.VerifyPeerCertificate != nil {
748 if err := c.config.VerifyPeerCertificate(certificates, c.verifiedChains); err != nil {
749 c.sendAlert(alertBadCertificate)
758 switch certs[0].PublicKey.(type) {
759 case *ecdsa.PublicKey, *rsa.PublicKey:
761 c.sendAlert(alertUnsupportedCertificate)
762 return fmt.Errorf("tls: client's certificate contains an unsupported public key of type %T", certs[0].PublicKey)
765 c.peerCertificates = certs
766 c.ocspResponse = certificate.OCSPStaple
767 c.scts = certificate.SignedCertificateTimestamps
771 // setCipherSuite sets a cipherSuite with the given id as the serverHandshakeState
772 // suite if that cipher suite is acceptable to use.
773 // It returns a bool indicating if the suite was set.
774 func (hs *serverHandshakeState) setCipherSuite(id uint16, supportedCipherSuites []uint16, version uint16) bool {
775 for _, supported := range supportedCipherSuites {
777 candidate := cipherSuiteByID(id)
778 if candidate == nil {
781 // Don't select a ciphersuite which we can't
782 // support for this client.
783 if candidate.flags&suiteECDHE != 0 {
787 if candidate.flags&suiteECDSA != 0 {
791 } else if !hs.rsaSignOk {
794 } else if !hs.rsaDecryptOk {
797 if version < VersionTLS12 && candidate.flags&suiteTLS12 != 0 {
807 func clientHelloInfo(c *Conn, clientHello *clientHelloMsg) *ClientHelloInfo {
808 supportedVersions := clientHello.supportedVersions
809 if len(clientHello.supportedVersions) == 0 {
810 supportedVersions = supportedVersionsFromMax(clientHello.vers)
813 return &ClientHelloInfo{
814 CipherSuites: clientHello.cipherSuites,
815 ServerName: clientHello.serverName,
816 SupportedCurves: clientHello.supportedCurves,
817 SupportedPoints: clientHello.supportedPoints,
818 SignatureSchemes: clientHello.supportedSignatureAlgorithms,
819 SupportedProtos: clientHello.alpnProtocols,
820 SupportedVersions: supportedVersions,