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(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 foundCompression := false
179 // We only support null compression, so check that the client offered it.
180 for _, compression := range hs.clientHello.compressionMethods {
181 if compression == compressionNone {
182 foundCompression = true
187 if !foundCompression {
188 c.sendAlert(alertHandshakeFailure)
189 return errors.New("tls: client does not support uncompressed connections")
192 hs.hello.random = make([]byte, 32)
193 serverRandom := hs.hello.random
194 // Downgrade protection canaries. See RFC 8446, Section 4.1.3.
195 maxVers := c.config.maxSupportedVersion()
196 if maxVers >= VersionTLS12 && c.vers < maxVers {
197 if c.vers == VersionTLS12 {
198 copy(serverRandom[24:], downgradeCanaryTLS12)
200 copy(serverRandom[24:], downgradeCanaryTLS11)
202 serverRandom = serverRandom[:24]
204 _, err := io.ReadFull(c.config.rand(), serverRandom)
206 c.sendAlert(alertInternalError)
210 if len(hs.clientHello.secureRenegotiation) != 0 {
211 c.sendAlert(alertHandshakeFailure)
212 return errors.New("tls: initial handshake had non-empty renegotiation extension")
215 hs.hello.secureRenegotiationSupported = hs.clientHello.secureRenegotiationSupported
216 hs.hello.compressionMethod = compressionNone
217 if len(hs.clientHello.serverName) > 0 {
218 c.serverName = hs.clientHello.serverName
221 if len(hs.clientHello.alpnProtocols) > 0 {
222 if selectedProto, fallback := mutualProtocol(hs.clientHello.alpnProtocols, c.config.NextProtos); !fallback {
223 hs.hello.alpnProtocol = selectedProto
224 c.clientProtocol = selectedProto
228 hs.cert, err = c.config.getCertificate(clientHelloInfo(c, hs.clientHello))
230 c.sendAlert(alertInternalError)
233 if hs.clientHello.scts {
234 hs.hello.scts = hs.cert.SignedCertificateTimestamps
237 hs.ecdheOk = supportsECDHE(c.config, hs.clientHello.supportedCurves, hs.clientHello.supportedPoints)
240 // Although omiting the ec_point_formats extension is permitted, some
241 // old OpenSSL version will refuse to handshake if not present.
243 // Per RFC 4492, section 5.1.2, implementations MUST support the
244 // uncompressed point format. See golang.org/issue/31943.
245 hs.hello.supportedPoints = []uint8{pointFormatUncompressed}
248 if priv, ok := hs.cert.PrivateKey.(crypto.Signer); ok {
249 switch priv.Public().(type) {
250 case *ecdsa.PublicKey:
252 case ed25519.PublicKey:
257 c.sendAlert(alertInternalError)
258 return fmt.Errorf("tls: unsupported signing key type (%T)", priv.Public())
261 if priv, ok := hs.cert.PrivateKey.(crypto.Decrypter); ok {
262 switch priv.Public().(type) {
264 hs.rsaDecryptOk = true
266 c.sendAlert(alertInternalError)
267 return fmt.Errorf("tls: unsupported decryption key type (%T)", priv.Public())
274 // supportsECDHE returns whether ECDHE key exchanges can be used with this
275 // pre-TLS 1.3 client.
276 func supportsECDHE(c *Config, supportedCurves []CurveID, supportedPoints []uint8) bool {
277 supportsCurve := false
278 for _, curve := range supportedCurves {
279 if c.supportsCurve(curve) {
285 supportsPointFormat := false
286 for _, pointFormat := range supportedPoints {
287 if pointFormat == pointFormatUncompressed {
288 supportsPointFormat = true
293 return supportsCurve && supportsPointFormat
296 func (hs *serverHandshakeState) pickCipherSuite() error {
299 var preferenceList, supportedList []uint16
300 if c.config.PreferServerCipherSuites {
301 preferenceList = c.config.cipherSuites()
302 supportedList = hs.clientHello.cipherSuites
304 preferenceList = hs.clientHello.cipherSuites
305 supportedList = c.config.cipherSuites()
308 hs.suite = selectCipherSuite(preferenceList, supportedList, hs.cipherSuiteOk)
310 c.sendAlert(alertHandshakeFailure)
311 return errors.New("tls: no cipher suite supported by both client and server")
314 for _, id := range hs.clientHello.cipherSuites {
315 if id == TLS_FALLBACK_SCSV {
316 // The client is doing a fallback connection. See RFC 7507.
317 if hs.clientHello.vers < c.config.maxSupportedVersion() {
318 c.sendAlert(alertInappropriateFallback)
319 return errors.New("tls: client using inappropriate protocol fallback")
328 func (hs *serverHandshakeState) cipherSuiteOk(c *cipherSuite) bool {
329 if c.flags&suiteECDHE != 0 {
333 if c.flags&suiteECSign != 0 {
337 } else if !hs.rsaSignOk {
340 } else if !hs.rsaDecryptOk {
343 if hs.c.vers < VersionTLS12 && c.flags&suiteTLS12 != 0 {
349 // checkForResumption reports whether we should perform resumption on this connection.
350 func (hs *serverHandshakeState) checkForResumption() bool {
353 if c.config.SessionTicketsDisabled {
357 plaintext, usedOldKey := c.decryptTicket(hs.clientHello.sessionTicket)
358 if plaintext == nil {
361 hs.sessionState = &sessionState{usedOldKey: usedOldKey}
362 ok := hs.sessionState.unmarshal(plaintext)
367 // Never resume a session for a different TLS version.
368 if c.vers != hs.sessionState.vers {
372 cipherSuiteOk := false
373 // Check that the client is still offering the ciphersuite in the session.
374 for _, id := range hs.clientHello.cipherSuites {
375 if id == hs.sessionState.cipherSuite {
384 // Check that we also support the ciphersuite from the session.
385 hs.suite = selectCipherSuite([]uint16{hs.sessionState.cipherSuite},
386 c.config.cipherSuites(), hs.cipherSuiteOk)
391 sessionHasClientCerts := len(hs.sessionState.certificates) != 0
392 needClientCerts := requiresClientCert(c.config.ClientAuth)
393 if needClientCerts && !sessionHasClientCerts {
396 if sessionHasClientCerts && c.config.ClientAuth == NoClientCert {
403 func (hs *serverHandshakeState) doResumeHandshake() error {
406 hs.hello.cipherSuite = hs.suite.id
407 // We echo the client's session ID in the ServerHello to let it know
408 // that we're doing a resumption.
409 hs.hello.sessionId = hs.clientHello.sessionId
410 hs.hello.ticketSupported = hs.sessionState.usedOldKey
411 hs.finishedHash = newFinishedHash(c.vers, hs.suite)
412 hs.finishedHash.discardHandshakeBuffer()
413 hs.finishedHash.Write(hs.clientHello.marshal())
414 hs.finishedHash.Write(hs.hello.marshal())
415 if _, err := c.writeRecord(recordTypeHandshake, hs.hello.marshal()); err != nil {
419 if err := c.processCertsFromClient(Certificate{
420 Certificate: hs.sessionState.certificates,
425 hs.masterSecret = hs.sessionState.masterSecret
430 func (hs *serverHandshakeState) doFullHandshake() error {
433 if hs.clientHello.ocspStapling && len(hs.cert.OCSPStaple) > 0 {
434 hs.hello.ocspStapling = true
437 hs.hello.ticketSupported = hs.clientHello.ticketSupported && !c.config.SessionTicketsDisabled
438 hs.hello.cipherSuite = hs.suite.id
440 hs.finishedHash = newFinishedHash(hs.c.vers, hs.suite)
441 if c.config.ClientAuth == NoClientCert {
442 // No need to keep a full record of the handshake if client
443 // certificates won't be used.
444 hs.finishedHash.discardHandshakeBuffer()
446 hs.finishedHash.Write(hs.clientHello.marshal())
447 hs.finishedHash.Write(hs.hello.marshal())
448 if _, err := c.writeRecord(recordTypeHandshake, hs.hello.marshal()); err != nil {
452 certMsg := new(certificateMsg)
453 certMsg.certificates = hs.cert.Certificate
454 hs.finishedHash.Write(certMsg.marshal())
455 if _, err := c.writeRecord(recordTypeHandshake, certMsg.marshal()); err != nil {
459 if hs.hello.ocspStapling {
460 certStatus := new(certificateStatusMsg)
461 certStatus.response = hs.cert.OCSPStaple
462 hs.finishedHash.Write(certStatus.marshal())
463 if _, err := c.writeRecord(recordTypeHandshake, certStatus.marshal()); err != nil {
468 keyAgreement := hs.suite.ka(c.vers)
469 skx, err := keyAgreement.generateServerKeyExchange(c.config, hs.cert, hs.clientHello, hs.hello)
471 c.sendAlert(alertHandshakeFailure)
475 hs.finishedHash.Write(skx.marshal())
476 if _, err := c.writeRecord(recordTypeHandshake, skx.marshal()); err != nil {
481 var certReq *certificateRequestMsg
482 if c.config.ClientAuth >= RequestClientCert {
483 // Request a client certificate
484 certReq = new(certificateRequestMsg)
485 certReq.certificateTypes = []byte{
486 byte(certTypeRSASign),
487 byte(certTypeECDSASign),
489 if c.vers >= VersionTLS12 {
490 certReq.hasSignatureAlgorithm = true
491 certReq.supportedSignatureAlgorithms = supportedSignatureAlgorithmsTLS12()
494 // An empty list of certificateAuthorities signals to
495 // the client that it may send any certificate in response
496 // to our request. When we know the CAs we trust, then
497 // we can send them down, so that the client can choose
498 // an appropriate certificate to give to us.
499 if c.config.ClientCAs != nil {
500 certReq.certificateAuthorities = c.config.ClientCAs.Subjects()
502 hs.finishedHash.Write(certReq.marshal())
503 if _, err := c.writeRecord(recordTypeHandshake, certReq.marshal()); err != nil {
508 helloDone := new(serverHelloDoneMsg)
509 hs.finishedHash.Write(helloDone.marshal())
510 if _, err := c.writeRecord(recordTypeHandshake, helloDone.marshal()); err != nil {
514 if _, err := c.flush(); err != nil {
518 var pub crypto.PublicKey // public key for client auth, if any
520 msg, err := c.readHandshake()
525 // If we requested a client certificate, then the client must send a
526 // certificate message, even if it's empty.
527 if c.config.ClientAuth >= RequestClientCert {
528 certMsg, ok := msg.(*certificateMsg)
530 c.sendAlert(alertUnexpectedMessage)
531 return unexpectedMessageError(certMsg, msg)
533 hs.finishedHash.Write(certMsg.marshal())
535 if err := c.processCertsFromClient(Certificate{
536 Certificate: certMsg.certificates,
540 if len(certMsg.certificates) != 0 {
541 pub = c.peerCertificates[0].PublicKey
544 msg, err = c.readHandshake()
550 // Get client key exchange
551 ckx, ok := msg.(*clientKeyExchangeMsg)
553 c.sendAlert(alertUnexpectedMessage)
554 return unexpectedMessageError(ckx, msg)
556 hs.finishedHash.Write(ckx.marshal())
558 preMasterSecret, err := keyAgreement.processClientKeyExchange(c.config, hs.cert, ckx, c.vers)
560 c.sendAlert(alertHandshakeFailure)
563 hs.masterSecret = masterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret, hs.clientHello.random, hs.hello.random)
564 if err := c.config.writeKeyLog(keyLogLabelTLS12, hs.clientHello.random, hs.masterSecret); err != nil {
565 c.sendAlert(alertInternalError)
569 // If we received a client cert in response to our certificate request message,
570 // the client will send us a certificateVerifyMsg immediately after the
571 // clientKeyExchangeMsg. This message is a digest of all preceding
572 // handshake-layer messages that is signed using the private key corresponding
573 // to the client's certificate. This allows us to verify that the client is in
574 // possession of the private key of the certificate.
575 if len(c.peerCertificates) > 0 {
576 msg, err = c.readHandshake()
580 certVerify, ok := msg.(*certificateVerifyMsg)
582 c.sendAlert(alertUnexpectedMessage)
583 return unexpectedMessageError(certVerify, msg)
587 var sigHash crypto.Hash
588 if c.vers >= VersionTLS12 {
589 if !isSupportedSignatureAlgorithm(certVerify.signatureAlgorithm, certReq.supportedSignatureAlgorithms) {
590 c.sendAlert(alertIllegalParameter)
591 return errors.New("tls: client certificate used with invalid signature algorithm")
593 sigType, sigHash, err = typeAndHashFromSignatureScheme(certVerify.signatureAlgorithm)
595 return c.sendAlert(alertInternalError)
598 sigType, sigHash, err = legacyTypeAndHashFromPublicKey(pub)
600 c.sendAlert(alertIllegalParameter)
605 signed := hs.finishedHash.hashForClientCertificate(sigType, sigHash, hs.masterSecret)
606 if err := verifyHandshakeSignature(sigType, pub, sigHash, signed, certVerify.signature); err != nil {
607 c.sendAlert(alertDecryptError)
608 return errors.New("tls: invalid signature by the client certificate: " + err.Error())
611 hs.finishedHash.Write(certVerify.marshal())
614 hs.finishedHash.discardHandshakeBuffer()
619 func (hs *serverHandshakeState) establishKeys() error {
622 clientMAC, serverMAC, clientKey, serverKey, clientIV, serverIV :=
623 keysFromMasterSecret(c.vers, hs.suite, hs.masterSecret, hs.clientHello.random, hs.hello.random, hs.suite.macLen, hs.suite.keyLen, hs.suite.ivLen)
625 var clientCipher, serverCipher interface{}
626 var clientHash, serverHash macFunction
628 if hs.suite.aead == nil {
629 clientCipher = hs.suite.cipher(clientKey, clientIV, true /* for reading */)
630 clientHash = hs.suite.mac(c.vers, clientMAC)
631 serverCipher = hs.suite.cipher(serverKey, serverIV, false /* not for reading */)
632 serverHash = hs.suite.mac(c.vers, serverMAC)
634 clientCipher = hs.suite.aead(clientKey, clientIV)
635 serverCipher = hs.suite.aead(serverKey, serverIV)
638 c.in.prepareCipherSpec(c.vers, clientCipher, clientHash)
639 c.out.prepareCipherSpec(c.vers, serverCipher, serverHash)
644 func (hs *serverHandshakeState) readFinished(out []byte) error {
647 if err := c.readChangeCipherSpec(); err != nil {
651 msg, err := c.readHandshake()
655 clientFinished, ok := msg.(*finishedMsg)
657 c.sendAlert(alertUnexpectedMessage)
658 return unexpectedMessageError(clientFinished, msg)
661 verify := hs.finishedHash.clientSum(hs.masterSecret)
662 if len(verify) != len(clientFinished.verifyData) ||
663 subtle.ConstantTimeCompare(verify, clientFinished.verifyData) != 1 {
664 c.sendAlert(alertHandshakeFailure)
665 return errors.New("tls: client's Finished message is incorrect")
668 hs.finishedHash.Write(clientFinished.marshal())
673 func (hs *serverHandshakeState) sendSessionTicket() error {
674 if !hs.hello.ticketSupported {
679 m := new(newSessionTicketMsg)
681 var certsFromClient [][]byte
682 for _, cert := range c.peerCertificates {
683 certsFromClient = append(certsFromClient, cert.Raw)
685 state := sessionState{
687 cipherSuite: hs.suite.id,
688 masterSecret: hs.masterSecret,
689 certificates: certsFromClient,
692 m.ticket, err = c.encryptTicket(state.marshal())
697 hs.finishedHash.Write(m.marshal())
698 if _, err := c.writeRecord(recordTypeHandshake, m.marshal()); err != nil {
705 func (hs *serverHandshakeState) sendFinished(out []byte) error {
708 if _, err := c.writeRecord(recordTypeChangeCipherSpec, []byte{1}); err != nil {
712 finished := new(finishedMsg)
713 finished.verifyData = hs.finishedHash.serverSum(hs.masterSecret)
714 hs.finishedHash.Write(finished.marshal())
715 if _, err := c.writeRecord(recordTypeHandshake, finished.marshal()); err != nil {
719 c.cipherSuite = hs.suite.id
720 copy(out, finished.verifyData)
725 // processCertsFromClient takes a chain of client certificates either from a
726 // Certificates message or from a sessionState and verifies them. It returns
727 // the public key of the leaf certificate.
728 func (c *Conn) processCertsFromClient(certificate Certificate) error {
729 certificates := certificate.Certificate
730 certs := make([]*x509.Certificate, len(certificates))
732 for i, asn1Data := range certificates {
733 if certs[i], err = x509.ParseCertificate(asn1Data); err != nil {
734 c.sendAlert(alertBadCertificate)
735 return errors.New("tls: failed to parse client certificate: " + err.Error())
739 if len(certs) == 0 && requiresClientCert(c.config.ClientAuth) {
740 c.sendAlert(alertBadCertificate)
741 return errors.New("tls: client didn't provide a certificate")
744 if c.config.ClientAuth >= VerifyClientCertIfGiven && len(certs) > 0 {
745 opts := x509.VerifyOptions{
746 IsBoring: isBoringCertificate,
748 Roots: c.config.ClientCAs,
749 CurrentTime: c.config.time(),
750 Intermediates: x509.NewCertPool(),
751 KeyUsages: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth},
754 for _, cert := range certs[1:] {
755 opts.Intermediates.AddCert(cert)
758 chains, err := certs[0].Verify(opts)
760 c.sendAlert(alertBadCertificate)
761 return errors.New("tls: failed to verify client certificate: " + err.Error())
764 c.verifiedChains = chains
767 if c.config.VerifyPeerCertificate != nil {
768 if err := c.config.VerifyPeerCertificate(certificates, c.verifiedChains); err != nil {
769 c.sendAlert(alertBadCertificate)
778 switch certs[0].PublicKey.(type) {
779 case *ecdsa.PublicKey, *rsa.PublicKey, ed25519.PublicKey:
781 c.sendAlert(alertUnsupportedCertificate)
782 return fmt.Errorf("tls: client certificate contains an unsupported public key of type %T", certs[0].PublicKey)
785 c.peerCertificates = certs
786 c.ocspResponse = certificate.OCSPStaple
787 c.scts = certificate.SignedCertificateTimestamps
791 func clientHelloInfo(c *Conn, clientHello *clientHelloMsg) *ClientHelloInfo {
792 supportedVersions := clientHello.supportedVersions
793 if len(clientHello.supportedVersions) == 0 {
794 supportedVersions = supportedVersionsFromMax(clientHello.vers)
797 return &ClientHelloInfo{
798 CipherSuites: clientHello.cipherSuites,
799 ServerName: clientHello.serverName,
800 SupportedCurves: clientHello.supportedCurves,
801 SupportedPoints: clientHello.supportedPoints,
802 SignatureSchemes: clientHello.supportedSignatureAlgorithms,
803 SupportedProtos: clientHello.alpnProtocols,
804 SupportedVersions: supportedVersions,