1 // Copyright 2018 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 type clientHandshakeStateTLS13 struct {
22 serverHello *serverHelloMsg
24 ecdheKey *ecdh.PrivateKey
30 certReq *certificateRequestMsgTLS13
33 suite *cipherSuiteTLS13
36 trafficSecret []byte // client_application_traffic_secret_0
39 // handshake requires hs.c, hs.hello, hs.serverHello, hs.ecdheKey, and,
40 // optionally, hs.session, hs.earlySecret and hs.binderKey to be set.
41 func (hs *clientHandshakeStateTLS13) handshake() error {
45 return errors.New("tls: internal error: TLS 1.3 reached in FIPS mode")
48 // The server must not select TLS 1.3 in a renegotiation. See RFC 8446,
49 // sections 4.1.2 and 4.1.3.
51 c.sendAlert(alertProtocolVersion)
52 return errors.New("tls: server selected TLS 1.3 in a renegotiation")
55 // Consistency check on the presence of a keyShare and its parameters.
56 if hs.ecdheKey == nil || len(hs.hello.keyShares) != 1 {
57 return c.sendAlert(alertInternalError)
60 if err := hs.checkServerHelloOrHRR(); err != nil {
64 hs.transcript = hs.suite.hash.New()
66 if err := transcriptMsg(hs.hello, hs.transcript); err != nil {
70 if bytes.Equal(hs.serverHello.random, helloRetryRequestRandom) {
71 if err := hs.sendDummyChangeCipherSpec(); err != nil {
74 if err := hs.processHelloRetryRequest(); err != nil {
79 if err := transcriptMsg(hs.serverHello, hs.transcript); err != nil {
84 if err := hs.processServerHello(); err != nil {
87 if err := hs.sendDummyChangeCipherSpec(); err != nil {
90 if err := hs.establishHandshakeKeys(); err != nil {
93 if err := hs.readServerParameters(); err != nil {
96 if err := hs.readServerCertificate(); err != nil {
99 if err := hs.readServerFinished(); err != nil {
102 if err := hs.sendClientCertificate(); err != nil {
105 if err := hs.sendClientFinished(); err != nil {
108 if _, err := c.flush(); err != nil {
112 c.isHandshakeComplete.Store(true)
117 // checkServerHelloOrHRR does validity checks that apply to both ServerHello and
118 // HelloRetryRequest messages. It sets hs.suite.
119 func (hs *clientHandshakeStateTLS13) checkServerHelloOrHRR() error {
122 if hs.serverHello.supportedVersion == 0 {
123 c.sendAlert(alertMissingExtension)
124 return errors.New("tls: server selected TLS 1.3 using the legacy version field")
127 if hs.serverHello.supportedVersion != VersionTLS13 {
128 c.sendAlert(alertIllegalParameter)
129 return errors.New("tls: server selected an invalid version after a HelloRetryRequest")
132 if hs.serverHello.vers != VersionTLS12 {
133 c.sendAlert(alertIllegalParameter)
134 return errors.New("tls: server sent an incorrect legacy version")
137 if hs.serverHello.ocspStapling ||
138 hs.serverHello.ticketSupported ||
139 hs.serverHello.secureRenegotiationSupported ||
140 len(hs.serverHello.secureRenegotiation) != 0 ||
141 len(hs.serverHello.alpnProtocol) != 0 ||
142 len(hs.serverHello.scts) != 0 {
143 c.sendAlert(alertUnsupportedExtension)
144 return errors.New("tls: server sent a ServerHello extension forbidden in TLS 1.3")
147 if !bytes.Equal(hs.hello.sessionId, hs.serverHello.sessionId) {
148 c.sendAlert(alertIllegalParameter)
149 return errors.New("tls: server did not echo the legacy session ID")
152 if hs.serverHello.compressionMethod != compressionNone {
153 c.sendAlert(alertIllegalParameter)
154 return errors.New("tls: server selected unsupported compression format")
157 selectedSuite := mutualCipherSuiteTLS13(hs.hello.cipherSuites, hs.serverHello.cipherSuite)
158 if hs.suite != nil && selectedSuite != hs.suite {
159 c.sendAlert(alertIllegalParameter)
160 return errors.New("tls: server changed cipher suite after a HelloRetryRequest")
162 if selectedSuite == nil {
163 c.sendAlert(alertIllegalParameter)
164 return errors.New("tls: server chose an unconfigured cipher suite")
166 hs.suite = selectedSuite
167 c.cipherSuite = hs.suite.id
172 // sendDummyChangeCipherSpec sends a ChangeCipherSpec record for compatibility
173 // with middleboxes that didn't implement TLS correctly. See RFC 8446, Appendix D.4.
174 func (hs *clientHandshakeStateTLS13) sendDummyChangeCipherSpec() error {
175 if hs.c.quic != nil {
181 hs.sentDummyCCS = true
183 return hs.c.writeChangeCipherRecord()
186 // processHelloRetryRequest handles the HRR in hs.serverHello, modifies and
187 // resends hs.hello, and reads the new ServerHello into hs.serverHello.
188 func (hs *clientHandshakeStateTLS13) processHelloRetryRequest() error {
191 // The first ClientHello gets double-hashed into the transcript upon a
192 // HelloRetryRequest. (The idea is that the server might offload transcript
193 // storage to the client in the cookie.) See RFC 8446, Section 4.4.1.
194 chHash := hs.transcript.Sum(nil)
195 hs.transcript.Reset()
196 hs.transcript.Write([]byte{typeMessageHash, 0, 0, uint8(len(chHash))})
197 hs.transcript.Write(chHash)
198 if err := transcriptMsg(hs.serverHello, hs.transcript); err != nil {
202 // The only HelloRetryRequest extensions we support are key_share and
203 // cookie, and clients must abort the handshake if the HRR would not result
204 // in any change in the ClientHello.
205 if hs.serverHello.selectedGroup == 0 && hs.serverHello.cookie == nil {
206 c.sendAlert(alertIllegalParameter)
207 return errors.New("tls: server sent an unnecessary HelloRetryRequest message")
210 if hs.serverHello.cookie != nil {
211 hs.hello.cookie = hs.serverHello.cookie
214 if hs.serverHello.serverShare.group != 0 {
215 c.sendAlert(alertDecodeError)
216 return errors.New("tls: received malformed key_share extension")
219 // If the server sent a key_share extension selecting a group, ensure it's
220 // a group we advertised but did not send a key share for, and send a key
221 // share for it this time.
222 if curveID := hs.serverHello.selectedGroup; curveID != 0 {
224 for _, id := range hs.hello.supportedCurves {
231 c.sendAlert(alertIllegalParameter)
232 return errors.New("tls: server selected unsupported group")
234 if sentID, _ := curveIDForCurve(hs.ecdheKey.Curve()); sentID == curveID {
235 c.sendAlert(alertIllegalParameter)
236 return errors.New("tls: server sent an unnecessary HelloRetryRequest key_share")
238 if _, ok := curveForCurveID(curveID); !ok {
239 c.sendAlert(alertInternalError)
240 return errors.New("tls: CurvePreferences includes unsupported curve")
242 key, err := generateECDHEKey(c.config.rand(), curveID)
244 c.sendAlert(alertInternalError)
248 hs.hello.keyShares = []keyShare{{group: curveID, data: key.PublicKey().Bytes()}}
252 if len(hs.hello.pskIdentities) > 0 {
253 pskSuite := cipherSuiteTLS13ByID(hs.session.cipherSuite)
255 return c.sendAlert(alertInternalError)
257 if pskSuite.hash == hs.suite.hash {
258 // Update binders and obfuscated_ticket_age.
259 ticketAge := c.config.time().Sub(time.Unix(int64(hs.session.createdAt), 0))
260 hs.hello.pskIdentities[0].obfuscatedTicketAge = uint32(ticketAge/time.Millisecond) + hs.session.ageAdd
262 transcript := hs.suite.hash.New()
263 transcript.Write([]byte{typeMessageHash, 0, 0, uint8(len(chHash))})
264 transcript.Write(chHash)
265 if err := transcriptMsg(hs.serverHello, transcript); err != nil {
268 helloBytes, err := hs.hello.marshalWithoutBinders()
272 transcript.Write(helloBytes)
273 pskBinders := [][]byte{hs.suite.finishedHash(hs.binderKey, transcript)}
274 if err := hs.hello.updateBinders(pskBinders); err != nil {
278 // Server selected a cipher suite incompatible with the PSK.
279 hs.hello.pskIdentities = nil
280 hs.hello.pskBinders = nil
284 if hs.hello.earlyData {
285 hs.hello.earlyData = false
286 c.quicRejectedEarlyData()
289 if _, err := hs.c.writeHandshakeRecord(hs.hello, hs.transcript); err != nil {
293 // serverHelloMsg is not included in the transcript
294 msg, err := c.readHandshake(nil)
299 serverHello, ok := msg.(*serverHelloMsg)
301 c.sendAlert(alertUnexpectedMessage)
302 return unexpectedMessageError(serverHello, msg)
304 hs.serverHello = serverHello
306 if err := hs.checkServerHelloOrHRR(); err != nil {
313 func (hs *clientHandshakeStateTLS13) processServerHello() error {
316 if bytes.Equal(hs.serverHello.random, helloRetryRequestRandom) {
317 c.sendAlert(alertUnexpectedMessage)
318 return errors.New("tls: server sent two HelloRetryRequest messages")
321 if len(hs.serverHello.cookie) != 0 {
322 c.sendAlert(alertUnsupportedExtension)
323 return errors.New("tls: server sent a cookie in a normal ServerHello")
326 if hs.serverHello.selectedGroup != 0 {
327 c.sendAlert(alertDecodeError)
328 return errors.New("tls: malformed key_share extension")
331 if hs.serverHello.serverShare.group == 0 {
332 c.sendAlert(alertIllegalParameter)
333 return errors.New("tls: server did not send a key share")
335 if sentID, _ := curveIDForCurve(hs.ecdheKey.Curve()); hs.serverHello.serverShare.group != sentID {
336 c.sendAlert(alertIllegalParameter)
337 return errors.New("tls: server selected unsupported group")
340 if !hs.serverHello.selectedIdentityPresent {
344 if int(hs.serverHello.selectedIdentity) >= len(hs.hello.pskIdentities) {
345 c.sendAlert(alertIllegalParameter)
346 return errors.New("tls: server selected an invalid PSK")
349 if len(hs.hello.pskIdentities) != 1 || hs.session == nil {
350 return c.sendAlert(alertInternalError)
352 pskSuite := cipherSuiteTLS13ByID(hs.session.cipherSuite)
354 return c.sendAlert(alertInternalError)
356 if pskSuite.hash != hs.suite.hash {
357 c.sendAlert(alertIllegalParameter)
358 return errors.New("tls: server selected an invalid PSK and cipher suite pair")
363 c.peerCertificates = hs.session.peerCertificates
364 c.activeCertHandles = hs.session.activeCertHandles
365 c.verifiedChains = hs.session.verifiedChains
366 c.ocspResponse = hs.session.ocspResponse
367 c.scts = hs.session.scts
371 func (hs *clientHandshakeStateTLS13) establishHandshakeKeys() error {
374 peerKey, err := hs.ecdheKey.Curve().NewPublicKey(hs.serverHello.serverShare.data)
376 c.sendAlert(alertIllegalParameter)
377 return errors.New("tls: invalid server key share")
379 sharedKey, err := hs.ecdheKey.ECDH(peerKey)
381 c.sendAlert(alertIllegalParameter)
382 return errors.New("tls: invalid server key share")
385 earlySecret := hs.earlySecret
387 earlySecret = hs.suite.extract(nil, nil)
390 handshakeSecret := hs.suite.extract(sharedKey,
391 hs.suite.deriveSecret(earlySecret, "derived", nil))
393 clientSecret := hs.suite.deriveSecret(handshakeSecret,
394 clientHandshakeTrafficLabel, hs.transcript)
395 c.out.setTrafficSecret(hs.suite, QUICEncryptionLevelHandshake, clientSecret)
396 serverSecret := hs.suite.deriveSecret(handshakeSecret,
397 serverHandshakeTrafficLabel, hs.transcript)
398 c.in.setTrafficSecret(hs.suite, QUICEncryptionLevelHandshake, serverSecret)
401 if c.hand.Len() != 0 {
402 c.sendAlert(alertUnexpectedMessage)
404 c.quicSetWriteSecret(QUICEncryptionLevelHandshake, hs.suite.id, clientSecret)
405 c.quicSetReadSecret(QUICEncryptionLevelHandshake, hs.suite.id, serverSecret)
408 err = c.config.writeKeyLog(keyLogLabelClientHandshake, hs.hello.random, clientSecret)
410 c.sendAlert(alertInternalError)
413 err = c.config.writeKeyLog(keyLogLabelServerHandshake, hs.hello.random, serverSecret)
415 c.sendAlert(alertInternalError)
419 hs.masterSecret = hs.suite.extract(nil,
420 hs.suite.deriveSecret(handshakeSecret, "derived", nil))
425 func (hs *clientHandshakeStateTLS13) readServerParameters() error {
428 msg, err := c.readHandshake(hs.transcript)
433 encryptedExtensions, ok := msg.(*encryptedExtensionsMsg)
435 c.sendAlert(alertUnexpectedMessage)
436 return unexpectedMessageError(encryptedExtensions, msg)
439 if err := checkALPN(hs.hello.alpnProtocols, encryptedExtensions.alpnProtocol, c.quic != nil); err != nil {
440 // RFC 8446 specifies that no_application_protocol is sent by servers, but
441 // does not specify how clients handle the selection of an incompatible protocol.
442 // RFC 9001 Section 8.1 specifies that QUIC clients send no_application_protocol
443 // in this case. Always sending no_application_protocol seems reasonable.
444 c.sendAlert(alertNoApplicationProtocol)
447 c.clientProtocol = encryptedExtensions.alpnProtocol
450 if encryptedExtensions.quicTransportParameters == nil {
451 // RFC 9001 Section 8.2.
452 c.sendAlert(alertMissingExtension)
453 return errors.New("tls: server did not send a quic_transport_parameters extension")
455 c.quicSetTransportParameters(encryptedExtensions.quicTransportParameters)
457 if encryptedExtensions.quicTransportParameters != nil {
458 c.sendAlert(alertUnsupportedExtension)
459 return errors.New("tls: server sent an unexpected quic_transport_parameters extension")
463 if !hs.hello.earlyData && encryptedExtensions.earlyData {
464 c.sendAlert(alertUnsupportedExtension)
465 return errors.New("tls: server sent an unexpected early_data extension")
467 if hs.hello.earlyData && !encryptedExtensions.earlyData {
468 c.quicRejectedEarlyData()
470 if encryptedExtensions.earlyData {
471 if hs.session.cipherSuite != c.cipherSuite {
472 c.sendAlert(alertHandshakeFailure)
473 return errors.New("tls: server accepted 0-RTT with the wrong cipher suite")
475 if hs.session.alpnProtocol != c.clientProtocol {
476 c.sendAlert(alertHandshakeFailure)
477 return errors.New("tls: server accepted 0-RTT with the wrong ALPN")
484 func (hs *clientHandshakeStateTLS13) readServerCertificate() error {
487 // Either a PSK or a certificate is always used, but not both.
488 // See RFC 8446, Section 4.1.1.
490 // Make sure the connection is still being verified whether or not this
491 // is a resumption. Resumptions currently don't reverify certificates so
492 // they don't call verifyServerCertificate. See Issue 31641.
493 if c.config.VerifyConnection != nil {
494 if err := c.config.VerifyConnection(c.connectionStateLocked()); err != nil {
495 c.sendAlert(alertBadCertificate)
502 msg, err := c.readHandshake(hs.transcript)
507 certReq, ok := msg.(*certificateRequestMsgTLS13)
511 msg, err = c.readHandshake(hs.transcript)
517 certMsg, ok := msg.(*certificateMsgTLS13)
519 c.sendAlert(alertUnexpectedMessage)
520 return unexpectedMessageError(certMsg, msg)
522 if len(certMsg.certificate.Certificate) == 0 {
523 c.sendAlert(alertDecodeError)
524 return errors.New("tls: received empty certificates message")
527 c.scts = certMsg.certificate.SignedCertificateTimestamps
528 c.ocspResponse = certMsg.certificate.OCSPStaple
530 if err := c.verifyServerCertificate(certMsg.certificate.Certificate); err != nil {
534 // certificateVerifyMsg is included in the transcript, but not until
535 // after we verify the handshake signature, since the state before
536 // this message was sent is used.
537 msg, err = c.readHandshake(nil)
542 certVerify, ok := msg.(*certificateVerifyMsg)
544 c.sendAlert(alertUnexpectedMessage)
545 return unexpectedMessageError(certVerify, msg)
548 // See RFC 8446, Section 4.4.3.
549 if !isSupportedSignatureAlgorithm(certVerify.signatureAlgorithm, supportedSignatureAlgorithms()) {
550 c.sendAlert(alertIllegalParameter)
551 return errors.New("tls: certificate used with invalid signature algorithm")
553 sigType, sigHash, err := typeAndHashFromSignatureScheme(certVerify.signatureAlgorithm)
555 return c.sendAlert(alertInternalError)
557 if sigType == signaturePKCS1v15 || sigHash == crypto.SHA1 {
558 c.sendAlert(alertIllegalParameter)
559 return errors.New("tls: certificate used with invalid signature algorithm")
561 signed := signedMessage(sigHash, serverSignatureContext, hs.transcript)
562 if err := verifyHandshakeSignature(sigType, c.peerCertificates[0].PublicKey,
563 sigHash, signed, certVerify.signature); err != nil {
564 c.sendAlert(alertDecryptError)
565 return errors.New("tls: invalid signature by the server certificate: " + err.Error())
568 if err := transcriptMsg(certVerify, hs.transcript); err != nil {
575 func (hs *clientHandshakeStateTLS13) readServerFinished() error {
578 // finishedMsg is included in the transcript, but not until after we
579 // check the client version, since the state before this message was
580 // sent is used during verification.
581 msg, err := c.readHandshake(nil)
586 finished, ok := msg.(*finishedMsg)
588 c.sendAlert(alertUnexpectedMessage)
589 return unexpectedMessageError(finished, msg)
592 expectedMAC := hs.suite.finishedHash(c.in.trafficSecret, hs.transcript)
593 if !hmac.Equal(expectedMAC, finished.verifyData) {
594 c.sendAlert(alertDecryptError)
595 return errors.New("tls: invalid server finished hash")
598 if err := transcriptMsg(finished, hs.transcript); err != nil {
602 // Derive secrets that take context through the server Finished.
604 hs.trafficSecret = hs.suite.deriveSecret(hs.masterSecret,
605 clientApplicationTrafficLabel, hs.transcript)
606 serverSecret := hs.suite.deriveSecret(hs.masterSecret,
607 serverApplicationTrafficLabel, hs.transcript)
608 c.in.setTrafficSecret(hs.suite, QUICEncryptionLevelApplication, serverSecret)
610 err = c.config.writeKeyLog(keyLogLabelClientTraffic, hs.hello.random, hs.trafficSecret)
612 c.sendAlert(alertInternalError)
615 err = c.config.writeKeyLog(keyLogLabelServerTraffic, hs.hello.random, serverSecret)
617 c.sendAlert(alertInternalError)
621 c.ekm = hs.suite.exportKeyingMaterial(hs.masterSecret, hs.transcript)
626 func (hs *clientHandshakeStateTLS13) sendClientCertificate() error {
629 if hs.certReq == nil {
633 cert, err := c.getClientCertificate(&CertificateRequestInfo{
634 AcceptableCAs: hs.certReq.certificateAuthorities,
635 SignatureSchemes: hs.certReq.supportedSignatureAlgorithms,
643 certMsg := new(certificateMsgTLS13)
645 certMsg.certificate = *cert
646 certMsg.scts = hs.certReq.scts && len(cert.SignedCertificateTimestamps) > 0
647 certMsg.ocspStapling = hs.certReq.ocspStapling && len(cert.OCSPStaple) > 0
649 if _, err := hs.c.writeHandshakeRecord(certMsg, hs.transcript); err != nil {
653 // If we sent an empty certificate message, skip the CertificateVerify.
654 if len(cert.Certificate) == 0 {
658 certVerifyMsg := new(certificateVerifyMsg)
659 certVerifyMsg.hasSignatureAlgorithm = true
661 certVerifyMsg.signatureAlgorithm, err = selectSignatureScheme(c.vers, cert, hs.certReq.supportedSignatureAlgorithms)
663 // getClientCertificate returned a certificate incompatible with the
664 // CertificateRequestInfo supported signature algorithms.
665 c.sendAlert(alertHandshakeFailure)
669 sigType, sigHash, err := typeAndHashFromSignatureScheme(certVerifyMsg.signatureAlgorithm)
671 return c.sendAlert(alertInternalError)
674 signed := signedMessage(sigHash, clientSignatureContext, hs.transcript)
675 signOpts := crypto.SignerOpts(sigHash)
676 if sigType == signatureRSAPSS {
677 signOpts = &rsa.PSSOptions{SaltLength: rsa.PSSSaltLengthEqualsHash, Hash: sigHash}
679 sig, err := cert.PrivateKey.(crypto.Signer).Sign(c.config.rand(), signed, signOpts)
681 c.sendAlert(alertInternalError)
682 return errors.New("tls: failed to sign handshake: " + err.Error())
684 certVerifyMsg.signature = sig
686 if _, err := hs.c.writeHandshakeRecord(certVerifyMsg, hs.transcript); err != nil {
693 func (hs *clientHandshakeStateTLS13) sendClientFinished() error {
696 finished := &finishedMsg{
697 verifyData: hs.suite.finishedHash(c.out.trafficSecret, hs.transcript),
700 if _, err := hs.c.writeHandshakeRecord(finished, hs.transcript); err != nil {
704 c.out.setTrafficSecret(hs.suite, QUICEncryptionLevelApplication, hs.trafficSecret)
706 if !c.config.SessionTicketsDisabled && c.config.ClientSessionCache != nil {
707 c.resumptionSecret = hs.suite.deriveSecret(hs.masterSecret,
708 resumptionLabel, hs.transcript)
712 if c.hand.Len() != 0 {
713 c.sendAlert(alertUnexpectedMessage)
715 c.quicSetWriteSecret(QUICEncryptionLevelApplication, hs.suite.id, hs.trafficSecret)
721 func (c *Conn) handleNewSessionTicket(msg *newSessionTicketMsgTLS13) error {
723 c.sendAlert(alertUnexpectedMessage)
724 return errors.New("tls: received new session ticket from a client")
727 if c.config.SessionTicketsDisabled || c.config.ClientSessionCache == nil {
731 // See RFC 8446, Section 4.6.1.
732 if msg.lifetime == 0 {
735 lifetime := time.Duration(msg.lifetime) * time.Second
736 if lifetime > maxSessionTicketLifetime {
737 c.sendAlert(alertIllegalParameter)
738 return errors.New("tls: received a session ticket with invalid lifetime")
741 // RFC 9001, Section 4.6.1
742 if c.quic != nil && msg.maxEarlyData != 0 && msg.maxEarlyData != 0xffffffff {
743 c.sendAlert(alertIllegalParameter)
744 return errors.New("tls: invalid early data for QUIC connection")
747 cipherSuite := cipherSuiteTLS13ByID(c.cipherSuite)
748 if cipherSuite == nil || c.resumptionSecret == nil {
749 return c.sendAlert(alertInternalError)
752 psk := cipherSuite.expandLabel(c.resumptionSecret, "resumption",
753 msg.nonce, cipherSuite.hash.Size())
755 session, err := c.sessionState()
757 c.sendAlert(alertInternalError)
761 session.useBy = uint64(c.config.time().Add(lifetime).Unix())
762 session.ageAdd = msg.ageAdd
763 session.EarlyData = c.quic != nil && msg.maxEarlyData == 0xffffffff // RFC 9001, Section 4.6.1
764 cs := &ClientSessionState{ticket: msg.label, session: session}
766 if cacheKey := c.clientSessionCacheKey(); cacheKey != "" {
767 c.config.ClientSessionCache.Put(cacheKey, cs)