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 if len(c.config.NextProtos) > 0 && len(hs.clientHello.alpnProtocols) > 0 {
221 selectedProto := mutualProtocol(hs.clientHello.alpnProtocols, c.config.NextProtos)
222 if selectedProto == "" {
223 c.sendAlert(alertNoApplicationProtocol)
224 return fmt.Errorf("tls: client requested unsupported application protocols (%s)", hs.clientHello.alpnProtocols)
226 hs.hello.alpnProtocol = selectedProto
227 c.clientProtocol = selectedProto
230 hs.cert, err = c.config.getCertificate(clientHelloInfo(hs.ctx, c, hs.clientHello))
232 if err == errNoCertificates {
233 c.sendAlert(alertUnrecognizedName)
235 c.sendAlert(alertInternalError)
239 if hs.clientHello.scts {
240 hs.hello.scts = hs.cert.SignedCertificateTimestamps
243 hs.ecdheOk = supportsECDHE(c.config, hs.clientHello.supportedCurves, hs.clientHello.supportedPoints)
246 // Although omitting the ec_point_formats extension is permitted, some
247 // old OpenSSL version will refuse to handshake if not present.
249 // Per RFC 4492, section 5.1.2, implementations MUST support the
250 // uncompressed point format. See golang.org/issue/31943.
251 hs.hello.supportedPoints = []uint8{pointFormatUncompressed}
254 if priv, ok := hs.cert.PrivateKey.(crypto.Signer); ok {
255 switch priv.Public().(type) {
256 case *ecdsa.PublicKey:
258 case ed25519.PublicKey:
263 c.sendAlert(alertInternalError)
264 return fmt.Errorf("tls: unsupported signing key type (%T)", priv.Public())
267 if priv, ok := hs.cert.PrivateKey.(crypto.Decrypter); ok {
268 switch priv.Public().(type) {
270 hs.rsaDecryptOk = true
272 c.sendAlert(alertInternalError)
273 return fmt.Errorf("tls: unsupported decryption key type (%T)", priv.Public())
280 // supportsECDHE returns whether ECDHE key exchanges can be used with this
281 // pre-TLS 1.3 client.
282 func supportsECDHE(c *Config, supportedCurves []CurveID, supportedPoints []uint8) bool {
283 supportsCurve := false
284 for _, curve := range supportedCurves {
285 if c.supportsCurve(curve) {
291 supportsPointFormat := false
292 for _, pointFormat := range supportedPoints {
293 if pointFormat == pointFormatUncompressed {
294 supportsPointFormat = true
299 return supportsCurve && supportsPointFormat
302 func (hs *serverHandshakeState) pickCipherSuite() error {
305 preferenceOrder := cipherSuitesPreferenceOrder
306 if !hasAESGCMHardwareSupport || !aesgcmPreferred(hs.clientHello.cipherSuites) {
307 preferenceOrder = cipherSuitesPreferenceOrderNoAES
310 configCipherSuites := c.config.cipherSuites()
311 preferenceList := make([]uint16, 0, len(configCipherSuites))
312 for _, suiteID := range preferenceOrder {
313 for _, id := range configCipherSuites {
315 preferenceList = append(preferenceList, id)
321 hs.suite = selectCipherSuite(preferenceList, hs.clientHello.cipherSuites, hs.cipherSuiteOk)
323 c.sendAlert(alertHandshakeFailure)
324 return errors.New("tls: no cipher suite supported by both client and server")
326 c.cipherSuite = hs.suite.id
328 for _, id := range hs.clientHello.cipherSuites {
329 if id == TLS_FALLBACK_SCSV {
330 // The client is doing a fallback connection. See RFC 7507.
331 if hs.clientHello.vers < c.config.maxSupportedVersion() {
332 c.sendAlert(alertInappropriateFallback)
333 return errors.New("tls: client using inappropriate protocol fallback")
342 func (hs *serverHandshakeState) cipherSuiteOk(c *cipherSuite) bool {
343 if c.flags&suiteECDHE != 0 {
347 if c.flags&suiteECSign != 0 {
351 } else if !hs.rsaSignOk {
354 } else if !hs.rsaDecryptOk {
357 if hs.c.vers < VersionTLS12 && c.flags&suiteTLS12 != 0 {
363 // checkForResumption reports whether we should perform resumption on this connection.
364 func (hs *serverHandshakeState) checkForResumption() bool {
367 if c.config.SessionTicketsDisabled {
371 plaintext, usedOldKey := c.decryptTicket(hs.clientHello.sessionTicket)
372 if plaintext == nil {
375 hs.sessionState = &sessionState{usedOldKey: usedOldKey}
376 ok := hs.sessionState.unmarshal(plaintext)
381 createdAt := time.Unix(int64(hs.sessionState.createdAt), 0)
382 if c.config.time().Sub(createdAt) > maxSessionTicketLifetime {
386 // Never resume a session for a different TLS version.
387 if c.vers != hs.sessionState.vers {
391 cipherSuiteOk := false
392 // Check that the client is still offering the ciphersuite in the session.
393 for _, id := range hs.clientHello.cipherSuites {
394 if id == hs.sessionState.cipherSuite {
403 // Check that we also support the ciphersuite from the session.
404 hs.suite = selectCipherSuite([]uint16{hs.sessionState.cipherSuite},
405 c.config.cipherSuites(), hs.cipherSuiteOk)
410 sessionHasClientCerts := len(hs.sessionState.certificates) != 0
411 needClientCerts := requiresClientCert(c.config.ClientAuth)
412 if needClientCerts && !sessionHasClientCerts {
415 if sessionHasClientCerts && c.config.ClientAuth == NoClientCert {
422 func (hs *serverHandshakeState) doResumeHandshake() error {
425 hs.hello.cipherSuite = hs.suite.id
426 c.cipherSuite = hs.suite.id
427 // We echo the client's session ID in the ServerHello to let it know
428 // that we're doing a resumption.
429 hs.hello.sessionId = hs.clientHello.sessionId
430 hs.hello.ticketSupported = hs.sessionState.usedOldKey
431 hs.finishedHash = newFinishedHash(c.vers, hs.suite)
432 hs.finishedHash.discardHandshakeBuffer()
433 hs.finishedHash.Write(hs.clientHello.marshal())
434 hs.finishedHash.Write(hs.hello.marshal())
435 if _, err := c.writeRecord(recordTypeHandshake, hs.hello.marshal()); err != nil {
439 if err := c.processCertsFromClient(Certificate{
440 Certificate: hs.sessionState.certificates,
445 if c.config.VerifyConnection != nil {
446 if err := c.config.VerifyConnection(c.connectionStateLocked()); err != nil {
447 c.sendAlert(alertBadCertificate)
452 hs.masterSecret = hs.sessionState.masterSecret
457 func (hs *serverHandshakeState) doFullHandshake() error {
460 if hs.clientHello.ocspStapling && len(hs.cert.OCSPStaple) > 0 {
461 hs.hello.ocspStapling = true
464 hs.hello.ticketSupported = hs.clientHello.ticketSupported && !c.config.SessionTicketsDisabled
465 hs.hello.cipherSuite = hs.suite.id
467 hs.finishedHash = newFinishedHash(hs.c.vers, hs.suite)
468 if c.config.ClientAuth == NoClientCert {
469 // No need to keep a full record of the handshake if client
470 // certificates won't be used.
471 hs.finishedHash.discardHandshakeBuffer()
473 hs.finishedHash.Write(hs.clientHello.marshal())
474 hs.finishedHash.Write(hs.hello.marshal())
475 if _, err := c.writeRecord(recordTypeHandshake, hs.hello.marshal()); err != nil {
479 certMsg := new(certificateMsg)
480 certMsg.certificates = hs.cert.Certificate
481 hs.finishedHash.Write(certMsg.marshal())
482 if _, err := c.writeRecord(recordTypeHandshake, certMsg.marshal()); err != nil {
486 if hs.hello.ocspStapling {
487 certStatus := new(certificateStatusMsg)
488 certStatus.response = hs.cert.OCSPStaple
489 hs.finishedHash.Write(certStatus.marshal())
490 if _, err := c.writeRecord(recordTypeHandshake, certStatus.marshal()); err != nil {
495 keyAgreement := hs.suite.ka(c.vers)
496 skx, err := keyAgreement.generateServerKeyExchange(c.config, hs.cert, hs.clientHello, hs.hello)
498 c.sendAlert(alertHandshakeFailure)
502 hs.finishedHash.Write(skx.marshal())
503 if _, err := c.writeRecord(recordTypeHandshake, skx.marshal()); err != nil {
508 var certReq *certificateRequestMsg
509 if c.config.ClientAuth >= RequestClientCert {
510 // Request a client certificate
511 certReq = new(certificateRequestMsg)
512 certReq.certificateTypes = []byte{
513 byte(certTypeRSASign),
514 byte(certTypeECDSASign),
516 if c.vers >= VersionTLS12 {
517 certReq.hasSignatureAlgorithm = true
518 certReq.supportedSignatureAlgorithms = supportedSignatureAlgorithms()
521 // An empty list of certificateAuthorities signals to
522 // the client that it may send any certificate in response
523 // to our request. When we know the CAs we trust, then
524 // we can send them down, so that the client can choose
525 // an appropriate certificate to give to us.
526 if c.config.ClientCAs != nil {
527 certReq.certificateAuthorities = c.config.ClientCAs.Subjects()
529 hs.finishedHash.Write(certReq.marshal())
530 if _, err := c.writeRecord(recordTypeHandshake, certReq.marshal()); err != nil {
535 helloDone := new(serverHelloDoneMsg)
536 hs.finishedHash.Write(helloDone.marshal())
537 if _, err := c.writeRecord(recordTypeHandshake, helloDone.marshal()); err != nil {
541 if _, err := c.flush(); err != nil {
545 var pub crypto.PublicKey // public key for client auth, if any
547 msg, err := c.readHandshake()
552 // If we requested a client certificate, then the client must send a
553 // certificate message, even if it's empty.
554 if c.config.ClientAuth >= RequestClientCert {
555 certMsg, ok := msg.(*certificateMsg)
557 c.sendAlert(alertUnexpectedMessage)
558 return unexpectedMessageError(certMsg, msg)
560 hs.finishedHash.Write(certMsg.marshal())
562 if err := c.processCertsFromClient(Certificate{
563 Certificate: certMsg.certificates,
567 if len(certMsg.certificates) != 0 {
568 pub = c.peerCertificates[0].PublicKey
571 msg, err = c.readHandshake()
576 if c.config.VerifyConnection != nil {
577 if err := c.config.VerifyConnection(c.connectionStateLocked()); err != nil {
578 c.sendAlert(alertBadCertificate)
583 // Get client key exchange
584 ckx, ok := msg.(*clientKeyExchangeMsg)
586 c.sendAlert(alertUnexpectedMessage)
587 return unexpectedMessageError(ckx, msg)
589 hs.finishedHash.Write(ckx.marshal())
591 preMasterSecret, err := keyAgreement.processClientKeyExchange(c.config, hs.cert, ckx, c.vers)
593 c.sendAlert(alertHandshakeFailure)
596 hs.masterSecret = masterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret, hs.clientHello.random, hs.hello.random)
597 if err := c.config.writeKeyLog(keyLogLabelTLS12, hs.clientHello.random, hs.masterSecret); err != nil {
598 c.sendAlert(alertInternalError)
602 // If we received a client cert in response to our certificate request message,
603 // the client will send us a certificateVerifyMsg immediately after the
604 // clientKeyExchangeMsg. This message is a digest of all preceding
605 // handshake-layer messages that is signed using the private key corresponding
606 // to the client's certificate. This allows us to verify that the client is in
607 // possession of the private key of the certificate.
608 if len(c.peerCertificates) > 0 {
609 msg, err = c.readHandshake()
613 certVerify, ok := msg.(*certificateVerifyMsg)
615 c.sendAlert(alertUnexpectedMessage)
616 return unexpectedMessageError(certVerify, msg)
620 var sigHash crypto.Hash
621 if c.vers >= VersionTLS12 {
622 if !isSupportedSignatureAlgorithm(certVerify.signatureAlgorithm, certReq.supportedSignatureAlgorithms) {
623 c.sendAlert(alertIllegalParameter)
624 return errors.New("tls: client certificate used with invalid signature algorithm")
626 sigType, sigHash, err = typeAndHashFromSignatureScheme(certVerify.signatureAlgorithm)
628 return c.sendAlert(alertInternalError)
631 sigType, sigHash, err = legacyTypeAndHashFromPublicKey(pub)
633 c.sendAlert(alertIllegalParameter)
638 signed := hs.finishedHash.hashForClientCertificate(sigType, sigHash, hs.masterSecret)
639 if err := verifyHandshakeSignature(sigType, pub, sigHash, signed, certVerify.signature); err != nil {
640 c.sendAlert(alertDecryptError)
641 return errors.New("tls: invalid signature by the client certificate: " + err.Error())
644 hs.finishedHash.Write(certVerify.marshal())
647 hs.finishedHash.discardHandshakeBuffer()
652 func (hs *serverHandshakeState) establishKeys() error {
655 clientMAC, serverMAC, clientKey, serverKey, clientIV, serverIV :=
656 keysFromMasterSecret(c.vers, hs.suite, hs.masterSecret, hs.clientHello.random, hs.hello.random, hs.suite.macLen, hs.suite.keyLen, hs.suite.ivLen)
658 var clientCipher, serverCipher interface{}
659 var clientHash, serverHash hash.Hash
661 if hs.suite.aead == nil {
662 clientCipher = hs.suite.cipher(clientKey, clientIV, true /* for reading */)
663 clientHash = hs.suite.mac(clientMAC)
664 serverCipher = hs.suite.cipher(serverKey, serverIV, false /* not for reading */)
665 serverHash = hs.suite.mac(serverMAC)
667 clientCipher = hs.suite.aead(clientKey, clientIV)
668 serverCipher = hs.suite.aead(serverKey, serverIV)
671 c.in.prepareCipherSpec(c.vers, clientCipher, clientHash)
672 c.out.prepareCipherSpec(c.vers, serverCipher, serverHash)
677 func (hs *serverHandshakeState) readFinished(out []byte) error {
680 if err := c.readChangeCipherSpec(); err != nil {
684 msg, err := c.readHandshake()
688 clientFinished, ok := msg.(*finishedMsg)
690 c.sendAlert(alertUnexpectedMessage)
691 return unexpectedMessageError(clientFinished, msg)
694 verify := hs.finishedHash.clientSum(hs.masterSecret)
695 if len(verify) != len(clientFinished.verifyData) ||
696 subtle.ConstantTimeCompare(verify, clientFinished.verifyData) != 1 {
697 c.sendAlert(alertHandshakeFailure)
698 return errors.New("tls: client's Finished message is incorrect")
701 hs.finishedHash.Write(clientFinished.marshal())
706 func (hs *serverHandshakeState) sendSessionTicket() error {
707 // ticketSupported is set in a resumption handshake if the
708 // ticket from the client was encrypted with an old session
709 // ticket key and thus a refreshed ticket should be sent.
710 if !hs.hello.ticketSupported {
715 m := new(newSessionTicketMsg)
717 createdAt := uint64(c.config.time().Unix())
718 if hs.sessionState != nil {
719 // If this is re-wrapping an old key, then keep
720 // the original time it was created.
721 createdAt = hs.sessionState.createdAt
724 var certsFromClient [][]byte
725 for _, cert := range c.peerCertificates {
726 certsFromClient = append(certsFromClient, cert.Raw)
728 state := sessionState{
730 cipherSuite: hs.suite.id,
731 createdAt: createdAt,
732 masterSecret: hs.masterSecret,
733 certificates: certsFromClient,
736 m.ticket, err = c.encryptTicket(state.marshal())
741 hs.finishedHash.Write(m.marshal())
742 if _, err := c.writeRecord(recordTypeHandshake, m.marshal()); err != nil {
749 func (hs *serverHandshakeState) sendFinished(out []byte) error {
752 if _, err := c.writeRecord(recordTypeChangeCipherSpec, []byte{1}); err != nil {
756 finished := new(finishedMsg)
757 finished.verifyData = hs.finishedHash.serverSum(hs.masterSecret)
758 hs.finishedHash.Write(finished.marshal())
759 if _, err := c.writeRecord(recordTypeHandshake, finished.marshal()); err != nil {
763 copy(out, finished.verifyData)
768 // processCertsFromClient takes a chain of client certificates either from a
769 // Certificates message or from a sessionState and verifies them. It returns
770 // the public key of the leaf certificate.
771 func (c *Conn) processCertsFromClient(certificate Certificate) error {
772 certificates := certificate.Certificate
773 certs := make([]*x509.Certificate, len(certificates))
775 for i, asn1Data := range certificates {
776 if certs[i], err = x509.ParseCertificate(asn1Data); err != nil {
777 c.sendAlert(alertBadCertificate)
778 return errors.New("tls: failed to parse client certificate: " + err.Error())
782 if len(certs) == 0 && requiresClientCert(c.config.ClientAuth) {
783 c.sendAlert(alertBadCertificate)
784 return errors.New("tls: client didn't provide a certificate")
787 if c.config.ClientAuth >= VerifyClientCertIfGiven && len(certs) > 0 {
788 opts := x509.VerifyOptions{
789 IsBoring: isBoringCertificate,
791 Roots: c.config.ClientCAs,
792 CurrentTime: c.config.time(),
793 Intermediates: x509.NewCertPool(),
794 KeyUsages: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth},
797 for _, cert := range certs[1:] {
798 opts.Intermediates.AddCert(cert)
801 chains, err := certs[0].Verify(opts)
803 c.sendAlert(alertBadCertificate)
804 return errors.New("tls: failed to verify client certificate: " + err.Error())
807 c.verifiedChains = chains
810 c.peerCertificates = certs
811 c.ocspResponse = certificate.OCSPStaple
812 c.scts = certificate.SignedCertificateTimestamps
815 switch certs[0].PublicKey.(type) {
816 case *ecdsa.PublicKey, *rsa.PublicKey, ed25519.PublicKey:
818 c.sendAlert(alertUnsupportedCertificate)
819 return fmt.Errorf("tls: client certificate contains an unsupported public key of type %T", certs[0].PublicKey)
823 if c.config.VerifyPeerCertificate != nil {
824 if err := c.config.VerifyPeerCertificate(certificates, c.verifiedChains); err != nil {
825 c.sendAlert(alertBadCertificate)
833 func clientHelloInfo(ctx context.Context, c *Conn, clientHello *clientHelloMsg) *ClientHelloInfo {
834 supportedVersions := clientHello.supportedVersions
835 if len(clientHello.supportedVersions) == 0 {
836 supportedVersions = supportedVersionsFromMax(clientHello.vers)
839 return &ClientHelloInfo{
840 CipherSuites: clientHello.cipherSuites,
841 ServerName: clientHello.serverName,
842 SupportedCurves: clientHello.supportedCurves,
843 SupportedPoints: clientHello.supportedPoints,
844 SignatureSchemes: clientHello.supportedSignatureAlgorithms,
845 SupportedProtos: clientHello.alpnProtocols,
846 SupportedVersions: supportedVersions,