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.
23 // serverHandshakeState contains details of a server handshake in progress.
24 // It's discarded once the handshake has completed.
25 type serverHandshakeState struct {
28 clientHello *clientHelloMsg
35 sessionState *sessionState
36 finishedHash finishedHash
41 // serverHandshake performs a TLS handshake as a server.
42 func (c *Conn) serverHandshake(ctx context.Context) error {
43 clientHello, err := c.readClientHello(ctx)
48 if c.vers == VersionTLS13 {
49 hs := serverHandshakeStateTLS13{
52 clientHello: clientHello,
57 hs := serverHandshakeState{
60 clientHello: clientHello,
65 func (hs *serverHandshakeState) handshake() error {
68 if err := hs.processClientHello(); err != nil {
72 // For an overview of TLS handshaking, see RFC 5246, Section 7.3.
74 if hs.checkForResumption() {
75 // The client has included a session ticket and so we do an abbreviated handshake.
77 if err := hs.doResumeHandshake(); err != nil {
80 if err := hs.establishKeys(); err != nil {
83 if err := hs.sendSessionTicket(); err != nil {
86 if err := hs.sendFinished(c.serverFinished[:]); err != nil {
89 if _, err := c.flush(); err != nil {
92 c.clientFinishedIsFirst = false
93 if err := hs.readFinished(nil); err != nil {
97 // The client didn't include a session ticket, or it wasn't
98 // valid so we do a full handshake.
99 if err := hs.pickCipherSuite(); err != nil {
102 if err := hs.doFullHandshake(); err != nil {
105 if err := hs.establishKeys(); err != nil {
108 if err := hs.readFinished(c.clientFinished[:]); err != nil {
111 c.clientFinishedIsFirst = true
113 if err := hs.sendSessionTicket(); err != nil {
116 if err := hs.sendFinished(nil); err != nil {
119 if _, err := c.flush(); err != nil {
124 c.ekm = ekmFromMasterSecret(c.vers, hs.suite, hs.masterSecret, hs.clientHello.random, hs.hello.random)
125 atomic.StoreUint32(&c.handshakeStatus, 1)
130 // readClientHello reads a ClientHello message and selects the protocol version.
131 func (c *Conn) readClientHello(ctx context.Context) (*clientHelloMsg, error) {
132 msg, err := c.readHandshake()
136 clientHello, ok := msg.(*clientHelloMsg)
138 c.sendAlert(alertUnexpectedMessage)
139 return nil, unexpectedMessageError(clientHello, msg)
142 var configForClient *Config
143 originalConfig := c.config
144 if c.config.GetConfigForClient != nil {
145 chi := clientHelloInfo(ctx, c, clientHello)
146 if configForClient, err = c.config.GetConfigForClient(chi); err != nil {
147 c.sendAlert(alertInternalError)
149 } else if configForClient != nil {
150 c.config = configForClient
153 c.ticketKeys = originalConfig.ticketKeys(configForClient)
155 clientVersions := clientHello.supportedVersions
156 if len(clientHello.supportedVersions) == 0 {
157 clientVersions = supportedVersionsFromMax(clientHello.vers)
159 c.vers, ok = c.config.mutualVersion(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 foundCompression := false
178 // We only support null compression, so check that the client offered it.
179 for _, compression := range hs.clientHello.compressionMethods {
180 if compression == compressionNone {
181 foundCompression = true
186 if !foundCompression {
187 c.sendAlert(alertHandshakeFailure)
188 return errors.New("tls: client does not support uncompressed connections")
191 hs.hello.random = make([]byte, 32)
192 serverRandom := hs.hello.random
193 // Downgrade protection canaries. See RFC 8446, Section 4.1.3.
194 maxVers := c.config.maxSupportedVersion()
195 if maxVers >= VersionTLS12 && c.vers < maxVers || testingOnlyForceDowngradeCanary {
196 if c.vers == VersionTLS12 {
197 copy(serverRandom[24:], downgradeCanaryTLS12)
199 copy(serverRandom[24:], downgradeCanaryTLS11)
201 serverRandom = serverRandom[:24]
203 _, err := io.ReadFull(c.config.rand(), serverRandom)
205 c.sendAlert(alertInternalError)
209 if len(hs.clientHello.secureRenegotiation) != 0 {
210 c.sendAlert(alertHandshakeFailure)
211 return errors.New("tls: initial handshake had non-empty renegotiation extension")
214 hs.hello.secureRenegotiationSupported = hs.clientHello.secureRenegotiationSupported
215 hs.hello.compressionMethod = compressionNone
216 if len(hs.clientHello.serverName) > 0 {
217 c.serverName = hs.clientHello.serverName
220 selectedProto, err := negotiateALPN(c.config.NextProtos, hs.clientHello.alpnProtocols)
222 c.sendAlert(alertNoApplicationProtocol)
225 hs.hello.alpnProtocol = selectedProto
226 c.clientProtocol = selectedProto
228 hs.cert, err = c.config.getCertificate(clientHelloInfo(hs.ctx, c, hs.clientHello))
230 if err == errNoCertificates {
231 c.sendAlert(alertUnrecognizedName)
233 c.sendAlert(alertInternalError)
237 if hs.clientHello.scts {
238 hs.hello.scts = hs.cert.SignedCertificateTimestamps
241 hs.ecdheOk = supportsECDHE(c.config, hs.clientHello.supportedCurves, hs.clientHello.supportedPoints)
244 // Although omitting the ec_point_formats extension is permitted, some
245 // old OpenSSL version will refuse to handshake if not present.
247 // Per RFC 4492, section 5.1.2, implementations MUST support the
248 // uncompressed point format. See golang.org/issue/31943.
249 hs.hello.supportedPoints = []uint8{pointFormatUncompressed}
252 if priv, ok := hs.cert.PrivateKey.(crypto.Signer); ok {
253 switch priv.Public().(type) {
254 case *ecdsa.PublicKey:
256 case ed25519.PublicKey:
261 c.sendAlert(alertInternalError)
262 return fmt.Errorf("tls: unsupported signing key type (%T)", priv.Public())
265 if priv, ok := hs.cert.PrivateKey.(crypto.Decrypter); ok {
266 switch priv.Public().(type) {
268 hs.rsaDecryptOk = true
270 c.sendAlert(alertInternalError)
271 return fmt.Errorf("tls: unsupported decryption key type (%T)", priv.Public())
278 // negotiateALPN picks a shared ALPN protocol that both sides support in server
279 // preference order. If ALPN is not configured or the peer doesn't support it,
280 // it returns "" and no error.
281 func negotiateALPN(serverProtos, clientProtos []string) (string, error) {
282 if len(serverProtos) == 0 || len(clientProtos) == 0 {
285 var http11fallback bool
286 for _, s := range serverProtos {
287 for _, c := range clientProtos {
291 if s == "h2" && c == "http/1.1" {
292 http11fallback = true
296 // As a special case, let http/1.1 clients connect to h2 servers as if they
297 // didn't support ALPN. We used not to enforce protocol overlap, so over
298 // time a number of HTTP servers were configured with only "h2", but
299 // expected to accept connections from "http/1.1" clients. See Issue 46310.
303 return "", fmt.Errorf("tls: client requested unsupported application protocols (%s)", clientProtos)
306 // supportsECDHE returns whether ECDHE key exchanges can be used with this
307 // pre-TLS 1.3 client.
308 func supportsECDHE(c *Config, supportedCurves []CurveID, supportedPoints []uint8) bool {
309 supportsCurve := false
310 for _, curve := range supportedCurves {
311 if c.supportsCurve(curve) {
317 supportsPointFormat := false
318 for _, pointFormat := range supportedPoints {
319 if pointFormat == pointFormatUncompressed {
320 supportsPointFormat = true
325 return supportsCurve && supportsPointFormat
328 func (hs *serverHandshakeState) pickCipherSuite() error {
331 preferenceOrder := cipherSuitesPreferenceOrder
332 if !hasAESGCMHardwareSupport || !aesgcmPreferred(hs.clientHello.cipherSuites) {
333 preferenceOrder = cipherSuitesPreferenceOrderNoAES
336 configCipherSuites := c.config.cipherSuites()
337 preferenceList := make([]uint16, 0, len(configCipherSuites))
338 for _, suiteID := range preferenceOrder {
339 for _, id := range configCipherSuites {
341 preferenceList = append(preferenceList, id)
347 hs.suite = selectCipherSuite(preferenceList, hs.clientHello.cipherSuites, hs.cipherSuiteOk)
349 c.sendAlert(alertHandshakeFailure)
350 return errors.New("tls: no cipher suite supported by both client and server")
352 c.cipherSuite = hs.suite.id
354 for _, id := range hs.clientHello.cipherSuites {
355 if id == TLS_FALLBACK_SCSV {
356 // The client is doing a fallback connection. See RFC 7507.
357 if hs.clientHello.vers < c.config.maxSupportedVersion() {
358 c.sendAlert(alertInappropriateFallback)
359 return errors.New("tls: client using inappropriate protocol fallback")
368 func (hs *serverHandshakeState) cipherSuiteOk(c *cipherSuite) bool {
369 if c.flags&suiteECDHE != 0 {
373 if c.flags&suiteECSign != 0 {
377 } else if !hs.rsaSignOk {
380 } else if !hs.rsaDecryptOk {
383 if hs.c.vers < VersionTLS12 && c.flags&suiteTLS12 != 0 {
389 // checkForResumption reports whether we should perform resumption on this connection.
390 func (hs *serverHandshakeState) checkForResumption() bool {
393 if c.config.SessionTicketsDisabled {
397 plaintext, usedOldKey := c.decryptTicket(hs.clientHello.sessionTicket)
398 if plaintext == nil {
401 hs.sessionState = &sessionState{usedOldKey: usedOldKey}
402 ok := hs.sessionState.unmarshal(plaintext)
407 createdAt := time.Unix(int64(hs.sessionState.createdAt), 0)
408 if c.config.time().Sub(createdAt) > maxSessionTicketLifetime {
412 // Never resume a session for a different TLS version.
413 if c.vers != hs.sessionState.vers {
417 cipherSuiteOk := false
418 // Check that the client is still offering the ciphersuite in the session.
419 for _, id := range hs.clientHello.cipherSuites {
420 if id == hs.sessionState.cipherSuite {
429 // Check that we also support the ciphersuite from the session.
430 hs.suite = selectCipherSuite([]uint16{hs.sessionState.cipherSuite},
431 c.config.cipherSuites(), hs.cipherSuiteOk)
436 sessionHasClientCerts := len(hs.sessionState.certificates) != 0
437 needClientCerts := requiresClientCert(c.config.ClientAuth)
438 if needClientCerts && !sessionHasClientCerts {
441 if sessionHasClientCerts && c.config.ClientAuth == NoClientCert {
448 func (hs *serverHandshakeState) doResumeHandshake() error {
451 hs.hello.cipherSuite = hs.suite.id
452 c.cipherSuite = hs.suite.id
453 // We echo the client's session ID in the ServerHello to let it know
454 // that we're doing a resumption.
455 hs.hello.sessionId = hs.clientHello.sessionId
456 hs.hello.ticketSupported = hs.sessionState.usedOldKey
457 hs.finishedHash = newFinishedHash(c.vers, hs.suite)
458 hs.finishedHash.discardHandshakeBuffer()
459 hs.finishedHash.Write(hs.clientHello.marshal())
460 hs.finishedHash.Write(hs.hello.marshal())
461 if _, err := c.writeRecord(recordTypeHandshake, hs.hello.marshal()); err != nil {
465 if err := c.processCertsFromClient(Certificate{
466 Certificate: hs.sessionState.certificates,
471 if c.config.VerifyConnection != nil {
472 if err := c.config.VerifyConnection(c.connectionStateLocked()); err != nil {
473 c.sendAlert(alertBadCertificate)
478 hs.masterSecret = hs.sessionState.masterSecret
483 func (hs *serverHandshakeState) doFullHandshake() error {
486 if hs.clientHello.ocspStapling && len(hs.cert.OCSPStaple) > 0 {
487 hs.hello.ocspStapling = true
490 hs.hello.ticketSupported = hs.clientHello.ticketSupported && !c.config.SessionTicketsDisabled
491 hs.hello.cipherSuite = hs.suite.id
493 hs.finishedHash = newFinishedHash(hs.c.vers, hs.suite)
494 if c.config.ClientAuth == NoClientCert {
495 // No need to keep a full record of the handshake if client
496 // certificates won't be used.
497 hs.finishedHash.discardHandshakeBuffer()
499 hs.finishedHash.Write(hs.clientHello.marshal())
500 hs.finishedHash.Write(hs.hello.marshal())
501 if _, err := c.writeRecord(recordTypeHandshake, hs.hello.marshal()); err != nil {
505 certMsg := new(certificateMsg)
506 certMsg.certificates = hs.cert.Certificate
507 hs.finishedHash.Write(certMsg.marshal())
508 if _, err := c.writeRecord(recordTypeHandshake, certMsg.marshal()); err != nil {
512 if hs.hello.ocspStapling {
513 certStatus := new(certificateStatusMsg)
514 certStatus.response = hs.cert.OCSPStaple
515 hs.finishedHash.Write(certStatus.marshal())
516 if _, err := c.writeRecord(recordTypeHandshake, certStatus.marshal()); err != nil {
521 keyAgreement := hs.suite.ka(c.vers)
522 skx, err := keyAgreement.generateServerKeyExchange(c.config, hs.cert, hs.clientHello, hs.hello)
524 c.sendAlert(alertHandshakeFailure)
528 hs.finishedHash.Write(skx.marshal())
529 if _, err := c.writeRecord(recordTypeHandshake, skx.marshal()); err != nil {
534 var certReq *certificateRequestMsg
535 if c.config.ClientAuth >= RequestClientCert {
536 // Request a client certificate
537 certReq = new(certificateRequestMsg)
538 certReq.certificateTypes = []byte{
539 byte(certTypeRSASign),
540 byte(certTypeECDSASign),
542 if c.vers >= VersionTLS12 {
543 certReq.hasSignatureAlgorithm = true
544 certReq.supportedSignatureAlgorithms = supportedSignatureAlgorithms()
547 // An empty list of certificateAuthorities signals to
548 // the client that it may send any certificate in response
549 // to our request. When we know the CAs we trust, then
550 // we can send them down, so that the client can choose
551 // an appropriate certificate to give to us.
552 if c.config.ClientCAs != nil {
553 certReq.certificateAuthorities = c.config.ClientCAs.Subjects()
555 hs.finishedHash.Write(certReq.marshal())
556 if _, err := c.writeRecord(recordTypeHandshake, certReq.marshal()); err != nil {
561 helloDone := new(serverHelloDoneMsg)
562 hs.finishedHash.Write(helloDone.marshal())
563 if _, err := c.writeRecord(recordTypeHandshake, helloDone.marshal()); err != nil {
567 if _, err := c.flush(); err != nil {
571 var pub crypto.PublicKey // public key for client auth, if any
573 msg, err := c.readHandshake()
578 // If we requested a client certificate, then the client must send a
579 // certificate message, even if it's empty.
580 if c.config.ClientAuth >= RequestClientCert {
581 certMsg, ok := msg.(*certificateMsg)
583 c.sendAlert(alertUnexpectedMessage)
584 return unexpectedMessageError(certMsg, msg)
586 hs.finishedHash.Write(certMsg.marshal())
588 if err := c.processCertsFromClient(Certificate{
589 Certificate: certMsg.certificates,
593 if len(certMsg.certificates) != 0 {
594 pub = c.peerCertificates[0].PublicKey
597 msg, err = c.readHandshake()
602 if c.config.VerifyConnection != nil {
603 if err := c.config.VerifyConnection(c.connectionStateLocked()); err != nil {
604 c.sendAlert(alertBadCertificate)
609 // Get client key exchange
610 ckx, ok := msg.(*clientKeyExchangeMsg)
612 c.sendAlert(alertUnexpectedMessage)
613 return unexpectedMessageError(ckx, msg)
615 hs.finishedHash.Write(ckx.marshal())
617 preMasterSecret, err := keyAgreement.processClientKeyExchange(c.config, hs.cert, ckx, c.vers)
619 c.sendAlert(alertHandshakeFailure)
622 hs.masterSecret = masterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret, hs.clientHello.random, hs.hello.random)
623 if err := c.config.writeKeyLog(keyLogLabelTLS12, hs.clientHello.random, hs.masterSecret); err != nil {
624 c.sendAlert(alertInternalError)
628 // If we received a client cert in response to our certificate request message,
629 // the client will send us a certificateVerifyMsg immediately after the
630 // clientKeyExchangeMsg. This message is a digest of all preceding
631 // handshake-layer messages that is signed using the private key corresponding
632 // to the client's certificate. This allows us to verify that the client is in
633 // possession of the private key of the certificate.
634 if len(c.peerCertificates) > 0 {
635 msg, err = c.readHandshake()
639 certVerify, ok := msg.(*certificateVerifyMsg)
641 c.sendAlert(alertUnexpectedMessage)
642 return unexpectedMessageError(certVerify, msg)
646 var sigHash crypto.Hash
647 if c.vers >= VersionTLS12 {
648 if !isSupportedSignatureAlgorithm(certVerify.signatureAlgorithm, certReq.supportedSignatureAlgorithms) {
649 c.sendAlert(alertIllegalParameter)
650 return errors.New("tls: client certificate used with invalid signature algorithm")
652 sigType, sigHash, err = typeAndHashFromSignatureScheme(certVerify.signatureAlgorithm)
654 return c.sendAlert(alertInternalError)
657 sigType, sigHash, err = legacyTypeAndHashFromPublicKey(pub)
659 c.sendAlert(alertIllegalParameter)
664 signed := hs.finishedHash.hashForClientCertificate(sigType, sigHash, hs.masterSecret)
665 if err := verifyHandshakeSignature(sigType, pub, sigHash, signed, certVerify.signature); err != nil {
666 c.sendAlert(alertDecryptError)
667 return errors.New("tls: invalid signature by the client certificate: " + err.Error())
670 hs.finishedHash.Write(certVerify.marshal())
673 hs.finishedHash.discardHandshakeBuffer()
678 func (hs *serverHandshakeState) establishKeys() error {
681 clientMAC, serverMAC, clientKey, serverKey, clientIV, serverIV :=
682 keysFromMasterSecret(c.vers, hs.suite, hs.masterSecret, hs.clientHello.random, hs.hello.random, hs.suite.macLen, hs.suite.keyLen, hs.suite.ivLen)
684 var clientCipher, serverCipher interface{}
685 var clientHash, serverHash hash.Hash
687 if hs.suite.aead == nil {
688 clientCipher = hs.suite.cipher(clientKey, clientIV, true /* for reading */)
689 clientHash = hs.suite.mac(clientMAC)
690 serverCipher = hs.suite.cipher(serverKey, serverIV, false /* not for reading */)
691 serverHash = hs.suite.mac(serverMAC)
693 clientCipher = hs.suite.aead(clientKey, clientIV)
694 serverCipher = hs.suite.aead(serverKey, serverIV)
697 c.in.prepareCipherSpec(c.vers, clientCipher, clientHash)
698 c.out.prepareCipherSpec(c.vers, serverCipher, serverHash)
703 func (hs *serverHandshakeState) readFinished(out []byte) error {
706 if err := c.readChangeCipherSpec(); err != nil {
710 msg, err := c.readHandshake()
714 clientFinished, ok := msg.(*finishedMsg)
716 c.sendAlert(alertUnexpectedMessage)
717 return unexpectedMessageError(clientFinished, msg)
720 verify := hs.finishedHash.clientSum(hs.masterSecret)
721 if len(verify) != len(clientFinished.verifyData) ||
722 subtle.ConstantTimeCompare(verify, clientFinished.verifyData) != 1 {
723 c.sendAlert(alertHandshakeFailure)
724 return errors.New("tls: client's Finished message is incorrect")
727 hs.finishedHash.Write(clientFinished.marshal())
732 func (hs *serverHandshakeState) sendSessionTicket() error {
733 // ticketSupported is set in a resumption handshake if the
734 // ticket from the client was encrypted with an old session
735 // ticket key and thus a refreshed ticket should be sent.
736 if !hs.hello.ticketSupported {
741 m := new(newSessionTicketMsg)
743 createdAt := uint64(c.config.time().Unix())
744 if hs.sessionState != nil {
745 // If this is re-wrapping an old key, then keep
746 // the original time it was created.
747 createdAt = hs.sessionState.createdAt
750 var certsFromClient [][]byte
751 for _, cert := range c.peerCertificates {
752 certsFromClient = append(certsFromClient, cert.Raw)
754 state := sessionState{
756 cipherSuite: hs.suite.id,
757 createdAt: createdAt,
758 masterSecret: hs.masterSecret,
759 certificates: certsFromClient,
762 m.ticket, err = c.encryptTicket(state.marshal())
767 hs.finishedHash.Write(m.marshal())
768 if _, err := c.writeRecord(recordTypeHandshake, m.marshal()); err != nil {
775 func (hs *serverHandshakeState) sendFinished(out []byte) error {
778 if _, err := c.writeRecord(recordTypeChangeCipherSpec, []byte{1}); err != nil {
782 finished := new(finishedMsg)
783 finished.verifyData = hs.finishedHash.serverSum(hs.masterSecret)
784 hs.finishedHash.Write(finished.marshal())
785 if _, err := c.writeRecord(recordTypeHandshake, finished.marshal()); err != nil {
789 copy(out, finished.verifyData)
794 // processCertsFromClient takes a chain of client certificates either from a
795 // Certificates message or from a sessionState and verifies them. It returns
796 // the public key of the leaf certificate.
797 func (c *Conn) processCertsFromClient(certificate Certificate) error {
798 certificates := certificate.Certificate
799 certs := make([]*x509.Certificate, len(certificates))
801 for i, asn1Data := range certificates {
802 if certs[i], err = x509.ParseCertificate(asn1Data); err != nil {
803 c.sendAlert(alertBadCertificate)
804 return errors.New("tls: failed to parse client certificate: " + err.Error())
808 if len(certs) == 0 && requiresClientCert(c.config.ClientAuth) {
809 c.sendAlert(alertBadCertificate)
810 return errors.New("tls: client didn't provide a certificate")
813 if c.config.ClientAuth >= VerifyClientCertIfGiven && len(certs) > 0 {
814 opts := x509.VerifyOptions{
815 IsBoring: isBoringCertificate,
817 Roots: c.config.ClientCAs,
818 CurrentTime: c.config.time(),
819 Intermediates: x509.NewCertPool(),
820 KeyUsages: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth},
823 for _, cert := range certs[1:] {
824 opts.Intermediates.AddCert(cert)
827 chains, err := certs[0].Verify(opts)
829 c.sendAlert(alertBadCertificate)
830 return errors.New("tls: failed to verify client certificate: " + err.Error())
833 c.verifiedChains = chains
836 c.peerCertificates = certs
837 c.ocspResponse = certificate.OCSPStaple
838 c.scts = certificate.SignedCertificateTimestamps
841 switch certs[0].PublicKey.(type) {
842 case *ecdsa.PublicKey, *rsa.PublicKey, ed25519.PublicKey:
844 c.sendAlert(alertUnsupportedCertificate)
845 return fmt.Errorf("tls: client certificate contains an unsupported public key of type %T", certs[0].PublicKey)
849 if c.config.VerifyPeerCertificate != nil {
850 if err := c.config.VerifyPeerCertificate(certificates, c.verifiedChains); err != nil {
851 c.sendAlert(alertBadCertificate)
859 func clientHelloInfo(ctx context.Context, c *Conn, clientHello *clientHelloMsg) *ClientHelloInfo {
860 supportedVersions := clientHello.supportedVersions
861 if len(clientHello.supportedVersions) == 0 {
862 supportedVersions = supportedVersionsFromMax(clientHello.vers)
865 return &ClientHelloInfo{
866 CipherSuites: clientHello.cipherSuites,
867 ServerName: clientHello.serverName,
868 SupportedCurves: clientHello.supportedCurves,
869 SupportedPoints: clientHello.supportedPoints,
870 SignatureSchemes: clientHello.supportedSignatureAlgorithms,
871 SupportedProtos: clientHello.alpnProtocols,
872 SupportedVersions: supportedVersions,