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.extendedMasterSecret ||
140 hs.serverHello.secureRenegotiationSupported ||
141 len(hs.serverHello.secureRenegotiation) != 0 ||
142 len(hs.serverHello.alpnProtocol) != 0 ||
143 len(hs.serverHello.scts) != 0 {
144 c.sendAlert(alertUnsupportedExtension)
145 return errors.New("tls: server sent a ServerHello extension forbidden in TLS 1.3")
148 if !bytes.Equal(hs.hello.sessionId, hs.serverHello.sessionId) {
149 c.sendAlert(alertIllegalParameter)
150 return errors.New("tls: server did not echo the legacy session ID")
153 if hs.serverHello.compressionMethod != compressionNone {
154 c.sendAlert(alertIllegalParameter)
155 return errors.New("tls: server selected unsupported compression format")
158 selectedSuite := mutualCipherSuiteTLS13(hs.hello.cipherSuites, hs.serverHello.cipherSuite)
159 if hs.suite != nil && selectedSuite != hs.suite {
160 c.sendAlert(alertIllegalParameter)
161 return errors.New("tls: server changed cipher suite after a HelloRetryRequest")
163 if selectedSuite == nil {
164 c.sendAlert(alertIllegalParameter)
165 return errors.New("tls: server chose an unconfigured cipher suite")
167 hs.suite = selectedSuite
168 c.cipherSuite = hs.suite.id
173 // sendDummyChangeCipherSpec sends a ChangeCipherSpec record for compatibility
174 // with middleboxes that didn't implement TLS correctly. See RFC 8446, Appendix D.4.
175 func (hs *clientHandshakeStateTLS13) sendDummyChangeCipherSpec() error {
176 if hs.c.quic != nil {
182 hs.sentDummyCCS = true
184 return hs.c.writeChangeCipherRecord()
187 // processHelloRetryRequest handles the HRR in hs.serverHello, modifies and
188 // resends hs.hello, and reads the new ServerHello into hs.serverHello.
189 func (hs *clientHandshakeStateTLS13) processHelloRetryRequest() error {
192 // The first ClientHello gets double-hashed into the transcript upon a
193 // HelloRetryRequest. (The idea is that the server might offload transcript
194 // storage to the client in the cookie.) See RFC 8446, Section 4.4.1.
195 chHash := hs.transcript.Sum(nil)
196 hs.transcript.Reset()
197 hs.transcript.Write([]byte{typeMessageHash, 0, 0, uint8(len(chHash))})
198 hs.transcript.Write(chHash)
199 if err := transcriptMsg(hs.serverHello, hs.transcript); err != nil {
203 // The only HelloRetryRequest extensions we support are key_share and
204 // cookie, and clients must abort the handshake if the HRR would not result
205 // in any change in the ClientHello.
206 if hs.serverHello.selectedGroup == 0 && hs.serverHello.cookie == nil {
207 c.sendAlert(alertIllegalParameter)
208 return errors.New("tls: server sent an unnecessary HelloRetryRequest message")
211 if hs.serverHello.cookie != nil {
212 hs.hello.cookie = hs.serverHello.cookie
215 if hs.serverHello.serverShare.group != 0 {
216 c.sendAlert(alertDecodeError)
217 return errors.New("tls: received malformed key_share extension")
220 // If the server sent a key_share extension selecting a group, ensure it's
221 // a group we advertised but did not send a key share for, and send a key
222 // share for it this time.
223 if curveID := hs.serverHello.selectedGroup; curveID != 0 {
225 for _, id := range hs.hello.supportedCurves {
232 c.sendAlert(alertIllegalParameter)
233 return errors.New("tls: server selected unsupported group")
235 if sentID, _ := curveIDForCurve(hs.ecdheKey.Curve()); sentID == curveID {
236 c.sendAlert(alertIllegalParameter)
237 return errors.New("tls: server sent an unnecessary HelloRetryRequest key_share")
239 if _, ok := curveForCurveID(curveID); !ok {
240 c.sendAlert(alertInternalError)
241 return errors.New("tls: CurvePreferences includes unsupported curve")
243 key, err := generateECDHEKey(c.config.rand(), curveID)
245 c.sendAlert(alertInternalError)
249 hs.hello.keyShares = []keyShare{{group: curveID, data: key.PublicKey().Bytes()}}
253 if len(hs.hello.pskIdentities) > 0 {
254 pskSuite := cipherSuiteTLS13ByID(hs.session.cipherSuite)
256 return c.sendAlert(alertInternalError)
258 if pskSuite.hash == hs.suite.hash {
259 // Update binders and obfuscated_ticket_age.
260 ticketAge := c.config.time().Sub(time.Unix(int64(hs.session.createdAt), 0))
261 hs.hello.pskIdentities[0].obfuscatedTicketAge = uint32(ticketAge/time.Millisecond) + hs.session.ageAdd
263 transcript := hs.suite.hash.New()
264 transcript.Write([]byte{typeMessageHash, 0, 0, uint8(len(chHash))})
265 transcript.Write(chHash)
266 if err := transcriptMsg(hs.serverHello, transcript); err != nil {
269 helloBytes, err := hs.hello.marshalWithoutBinders()
273 transcript.Write(helloBytes)
274 pskBinders := [][]byte{hs.suite.finishedHash(hs.binderKey, transcript)}
275 if err := hs.hello.updateBinders(pskBinders); err != nil {
279 // Server selected a cipher suite incompatible with the PSK.
280 hs.hello.pskIdentities = nil
281 hs.hello.pskBinders = nil
285 if hs.hello.earlyData {
286 hs.hello.earlyData = false
287 c.quicRejectedEarlyData()
290 if _, err := hs.c.writeHandshakeRecord(hs.hello, hs.transcript); err != nil {
294 // serverHelloMsg is not included in the transcript
295 msg, err := c.readHandshake(nil)
300 serverHello, ok := msg.(*serverHelloMsg)
302 c.sendAlert(alertUnexpectedMessage)
303 return unexpectedMessageError(serverHello, msg)
305 hs.serverHello = serverHello
307 if err := hs.checkServerHelloOrHRR(); err != nil {
314 func (hs *clientHandshakeStateTLS13) processServerHello() error {
317 if bytes.Equal(hs.serverHello.random, helloRetryRequestRandom) {
318 c.sendAlert(alertUnexpectedMessage)
319 return errors.New("tls: server sent two HelloRetryRequest messages")
322 if len(hs.serverHello.cookie) != 0 {
323 c.sendAlert(alertUnsupportedExtension)
324 return errors.New("tls: server sent a cookie in a normal ServerHello")
327 if hs.serverHello.selectedGroup != 0 {
328 c.sendAlert(alertDecodeError)
329 return errors.New("tls: malformed key_share extension")
332 if hs.serverHello.serverShare.group == 0 {
333 c.sendAlert(alertIllegalParameter)
334 return errors.New("tls: server did not send a key share")
336 if sentID, _ := curveIDForCurve(hs.ecdheKey.Curve()); hs.serverHello.serverShare.group != sentID {
337 c.sendAlert(alertIllegalParameter)
338 return errors.New("tls: server selected unsupported group")
341 if !hs.serverHello.selectedIdentityPresent {
345 if int(hs.serverHello.selectedIdentity) >= len(hs.hello.pskIdentities) {
346 c.sendAlert(alertIllegalParameter)
347 return errors.New("tls: server selected an invalid PSK")
350 if len(hs.hello.pskIdentities) != 1 || hs.session == nil {
351 return c.sendAlert(alertInternalError)
353 pskSuite := cipherSuiteTLS13ByID(hs.session.cipherSuite)
355 return c.sendAlert(alertInternalError)
357 if pskSuite.hash != hs.suite.hash {
358 c.sendAlert(alertIllegalParameter)
359 return errors.New("tls: server selected an invalid PSK and cipher suite pair")
364 c.peerCertificates = hs.session.peerCertificates
365 c.activeCertHandles = hs.session.activeCertHandles
366 c.verifiedChains = hs.session.verifiedChains
367 c.ocspResponse = hs.session.ocspResponse
368 c.scts = hs.session.scts
372 func (hs *clientHandshakeStateTLS13) establishHandshakeKeys() error {
375 peerKey, err := hs.ecdheKey.Curve().NewPublicKey(hs.serverHello.serverShare.data)
377 c.sendAlert(alertIllegalParameter)
378 return errors.New("tls: invalid server key share")
380 sharedKey, err := hs.ecdheKey.ECDH(peerKey)
382 c.sendAlert(alertIllegalParameter)
383 return errors.New("tls: invalid server key share")
386 earlySecret := hs.earlySecret
388 earlySecret = hs.suite.extract(nil, nil)
391 handshakeSecret := hs.suite.extract(sharedKey,
392 hs.suite.deriveSecret(earlySecret, "derived", nil))
394 clientSecret := hs.suite.deriveSecret(handshakeSecret,
395 clientHandshakeTrafficLabel, hs.transcript)
396 c.out.setTrafficSecret(hs.suite, QUICEncryptionLevelHandshake, clientSecret)
397 serverSecret := hs.suite.deriveSecret(handshakeSecret,
398 serverHandshakeTrafficLabel, hs.transcript)
399 c.in.setTrafficSecret(hs.suite, QUICEncryptionLevelHandshake, serverSecret)
402 if c.hand.Len() != 0 {
403 c.sendAlert(alertUnexpectedMessage)
405 c.quicSetWriteSecret(QUICEncryptionLevelHandshake, hs.suite.id, clientSecret)
406 c.quicSetReadSecret(QUICEncryptionLevelHandshake, hs.suite.id, serverSecret)
409 err = c.config.writeKeyLog(keyLogLabelClientHandshake, hs.hello.random, clientSecret)
411 c.sendAlert(alertInternalError)
414 err = c.config.writeKeyLog(keyLogLabelServerHandshake, hs.hello.random, serverSecret)
416 c.sendAlert(alertInternalError)
420 hs.masterSecret = hs.suite.extract(nil,
421 hs.suite.deriveSecret(handshakeSecret, "derived", nil))
426 func (hs *clientHandshakeStateTLS13) readServerParameters() error {
429 msg, err := c.readHandshake(hs.transcript)
434 encryptedExtensions, ok := msg.(*encryptedExtensionsMsg)
436 c.sendAlert(alertUnexpectedMessage)
437 return unexpectedMessageError(encryptedExtensions, msg)
440 if err := checkALPN(hs.hello.alpnProtocols, encryptedExtensions.alpnProtocol, c.quic != nil); err != nil {
441 // RFC 8446 specifies that no_application_protocol is sent by servers, but
442 // does not specify how clients handle the selection of an incompatible protocol.
443 // RFC 9001 Section 8.1 specifies that QUIC clients send no_application_protocol
444 // in this case. Always sending no_application_protocol seems reasonable.
445 c.sendAlert(alertNoApplicationProtocol)
448 c.clientProtocol = encryptedExtensions.alpnProtocol
451 if encryptedExtensions.quicTransportParameters == nil {
452 // RFC 9001 Section 8.2.
453 c.sendAlert(alertMissingExtension)
454 return errors.New("tls: server did not send a quic_transport_parameters extension")
456 c.quicSetTransportParameters(encryptedExtensions.quicTransportParameters)
458 if encryptedExtensions.quicTransportParameters != nil {
459 c.sendAlert(alertUnsupportedExtension)
460 return errors.New("tls: server sent an unexpected quic_transport_parameters extension")
464 if !hs.hello.earlyData && encryptedExtensions.earlyData {
465 c.sendAlert(alertUnsupportedExtension)
466 return errors.New("tls: server sent an unexpected early_data extension")
468 if hs.hello.earlyData && !encryptedExtensions.earlyData {
469 c.quicRejectedEarlyData()
471 if encryptedExtensions.earlyData {
472 if hs.session.cipherSuite != c.cipherSuite {
473 c.sendAlert(alertHandshakeFailure)
474 return errors.New("tls: server accepted 0-RTT with the wrong cipher suite")
476 if hs.session.alpnProtocol != c.clientProtocol {
477 c.sendAlert(alertHandshakeFailure)
478 return errors.New("tls: server accepted 0-RTT with the wrong ALPN")
485 func (hs *clientHandshakeStateTLS13) readServerCertificate() error {
488 // Either a PSK or a certificate is always used, but not both.
489 // See RFC 8446, Section 4.1.1.
491 // Make sure the connection is still being verified whether or not this
492 // is a resumption. Resumptions currently don't reverify certificates so
493 // they don't call verifyServerCertificate. See Issue 31641.
494 if c.config.VerifyConnection != nil {
495 if err := c.config.VerifyConnection(c.connectionStateLocked()); err != nil {
496 c.sendAlert(alertBadCertificate)
503 msg, err := c.readHandshake(hs.transcript)
508 certReq, ok := msg.(*certificateRequestMsgTLS13)
512 msg, err = c.readHandshake(hs.transcript)
518 certMsg, ok := msg.(*certificateMsgTLS13)
520 c.sendAlert(alertUnexpectedMessage)
521 return unexpectedMessageError(certMsg, msg)
523 if len(certMsg.certificate.Certificate) == 0 {
524 c.sendAlert(alertDecodeError)
525 return errors.New("tls: received empty certificates message")
528 c.scts = certMsg.certificate.SignedCertificateTimestamps
529 c.ocspResponse = certMsg.certificate.OCSPStaple
531 if err := c.verifyServerCertificate(certMsg.certificate.Certificate); err != nil {
535 // certificateVerifyMsg is included in the transcript, but not until
536 // after we verify the handshake signature, since the state before
537 // this message was sent is used.
538 msg, err = c.readHandshake(nil)
543 certVerify, ok := msg.(*certificateVerifyMsg)
545 c.sendAlert(alertUnexpectedMessage)
546 return unexpectedMessageError(certVerify, msg)
549 // See RFC 8446, Section 4.4.3.
550 if !isSupportedSignatureAlgorithm(certVerify.signatureAlgorithm, supportedSignatureAlgorithms()) {
551 c.sendAlert(alertIllegalParameter)
552 return errors.New("tls: certificate used with invalid signature algorithm")
554 sigType, sigHash, err := typeAndHashFromSignatureScheme(certVerify.signatureAlgorithm)
556 return c.sendAlert(alertInternalError)
558 if sigType == signaturePKCS1v15 || sigHash == crypto.SHA1 {
559 c.sendAlert(alertIllegalParameter)
560 return errors.New("tls: certificate used with invalid signature algorithm")
562 signed := signedMessage(sigHash, serverSignatureContext, hs.transcript)
563 if err := verifyHandshakeSignature(sigType, c.peerCertificates[0].PublicKey,
564 sigHash, signed, certVerify.signature); err != nil {
565 c.sendAlert(alertDecryptError)
566 return errors.New("tls: invalid signature by the server certificate: " + err.Error())
569 if err := transcriptMsg(certVerify, hs.transcript); err != nil {
576 func (hs *clientHandshakeStateTLS13) readServerFinished() error {
579 // finishedMsg is included in the transcript, but not until after we
580 // check the client version, since the state before this message was
581 // sent is used during verification.
582 msg, err := c.readHandshake(nil)
587 finished, ok := msg.(*finishedMsg)
589 c.sendAlert(alertUnexpectedMessage)
590 return unexpectedMessageError(finished, msg)
593 expectedMAC := hs.suite.finishedHash(c.in.trafficSecret, hs.transcript)
594 if !hmac.Equal(expectedMAC, finished.verifyData) {
595 c.sendAlert(alertDecryptError)
596 return errors.New("tls: invalid server finished hash")
599 if err := transcriptMsg(finished, hs.transcript); err != nil {
603 // Derive secrets that take context through the server Finished.
605 hs.trafficSecret = hs.suite.deriveSecret(hs.masterSecret,
606 clientApplicationTrafficLabel, hs.transcript)
607 serverSecret := hs.suite.deriveSecret(hs.masterSecret,
608 serverApplicationTrafficLabel, hs.transcript)
609 c.in.setTrafficSecret(hs.suite, QUICEncryptionLevelApplication, serverSecret)
611 err = c.config.writeKeyLog(keyLogLabelClientTraffic, hs.hello.random, hs.trafficSecret)
613 c.sendAlert(alertInternalError)
616 err = c.config.writeKeyLog(keyLogLabelServerTraffic, hs.hello.random, serverSecret)
618 c.sendAlert(alertInternalError)
622 c.ekm = hs.suite.exportKeyingMaterial(hs.masterSecret, hs.transcript)
627 func (hs *clientHandshakeStateTLS13) sendClientCertificate() error {
630 if hs.certReq == nil {
634 cert, err := c.getClientCertificate(&CertificateRequestInfo{
635 AcceptableCAs: hs.certReq.certificateAuthorities,
636 SignatureSchemes: hs.certReq.supportedSignatureAlgorithms,
644 certMsg := new(certificateMsgTLS13)
646 certMsg.certificate = *cert
647 certMsg.scts = hs.certReq.scts && len(cert.SignedCertificateTimestamps) > 0
648 certMsg.ocspStapling = hs.certReq.ocspStapling && len(cert.OCSPStaple) > 0
650 if _, err := hs.c.writeHandshakeRecord(certMsg, hs.transcript); err != nil {
654 // If we sent an empty certificate message, skip the CertificateVerify.
655 if len(cert.Certificate) == 0 {
659 certVerifyMsg := new(certificateVerifyMsg)
660 certVerifyMsg.hasSignatureAlgorithm = true
662 certVerifyMsg.signatureAlgorithm, err = selectSignatureScheme(c.vers, cert, hs.certReq.supportedSignatureAlgorithms)
664 // getClientCertificate returned a certificate incompatible with the
665 // CertificateRequestInfo supported signature algorithms.
666 c.sendAlert(alertHandshakeFailure)
670 sigType, sigHash, err := typeAndHashFromSignatureScheme(certVerifyMsg.signatureAlgorithm)
672 return c.sendAlert(alertInternalError)
675 signed := signedMessage(sigHash, clientSignatureContext, hs.transcript)
676 signOpts := crypto.SignerOpts(sigHash)
677 if sigType == signatureRSAPSS {
678 signOpts = &rsa.PSSOptions{SaltLength: rsa.PSSSaltLengthEqualsHash, Hash: sigHash}
680 sig, err := cert.PrivateKey.(crypto.Signer).Sign(c.config.rand(), signed, signOpts)
682 c.sendAlert(alertInternalError)
683 return errors.New("tls: failed to sign handshake: " + err.Error())
685 certVerifyMsg.signature = sig
687 if _, err := hs.c.writeHandshakeRecord(certVerifyMsg, hs.transcript); err != nil {
694 func (hs *clientHandshakeStateTLS13) sendClientFinished() error {
697 finished := &finishedMsg{
698 verifyData: hs.suite.finishedHash(c.out.trafficSecret, hs.transcript),
701 if _, err := hs.c.writeHandshakeRecord(finished, hs.transcript); err != nil {
705 c.out.setTrafficSecret(hs.suite, QUICEncryptionLevelApplication, hs.trafficSecret)
707 if !c.config.SessionTicketsDisabled && c.config.ClientSessionCache != nil {
708 c.resumptionSecret = hs.suite.deriveSecret(hs.masterSecret,
709 resumptionLabel, hs.transcript)
713 if c.hand.Len() != 0 {
714 c.sendAlert(alertUnexpectedMessage)
716 c.quicSetWriteSecret(QUICEncryptionLevelApplication, hs.suite.id, hs.trafficSecret)
722 func (c *Conn) handleNewSessionTicket(msg *newSessionTicketMsgTLS13) error {
724 c.sendAlert(alertUnexpectedMessage)
725 return errors.New("tls: received new session ticket from a client")
728 if c.config.SessionTicketsDisabled || c.config.ClientSessionCache == nil {
732 // See RFC 8446, Section 4.6.1.
733 if msg.lifetime == 0 {
736 lifetime := time.Duration(msg.lifetime) * time.Second
737 if lifetime > maxSessionTicketLifetime {
738 c.sendAlert(alertIllegalParameter)
739 return errors.New("tls: received a session ticket with invalid lifetime")
742 // RFC 9001, Section 4.6.1
743 if c.quic != nil && msg.maxEarlyData != 0 && msg.maxEarlyData != 0xffffffff {
744 c.sendAlert(alertIllegalParameter)
745 return errors.New("tls: invalid early data for QUIC connection")
748 cipherSuite := cipherSuiteTLS13ByID(c.cipherSuite)
749 if cipherSuite == nil || c.resumptionSecret == nil {
750 return c.sendAlert(alertInternalError)
753 psk := cipherSuite.expandLabel(c.resumptionSecret, "resumption",
754 msg.nonce, cipherSuite.hash.Size())
756 session, err := c.sessionState()
758 c.sendAlert(alertInternalError)
762 session.useBy = uint64(c.config.time().Add(lifetime).Unix())
763 session.ageAdd = msg.ageAdd
764 session.EarlyData = c.quic != nil && msg.maxEarlyData == 0xffffffff // RFC 9001, Section 4.6.1
765 cs := &ClientSessionState{ticket: msg.label, session: session}
767 if cacheKey := c.clientSessionCacheKey(); cacheKey != "" {
768 c.config.ClientSessionCache.Put(cacheKey, cs)