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 ecdheParams ecdheParameters
26 session *ClientSessionState
30 certReq *certificateRequestMsgTLS13
33 suite *cipherSuiteTLS13
36 trafficSecret []byte // client_application_traffic_secret_0
39 // handshake requires hs.c, hs.hello, hs.serverHello, hs.ecdheParams, 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.ecdheParams == 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()
65 hs.transcript.Write(hs.hello.marshal())
67 if bytes.Equal(hs.serverHello.random, helloRetryRequestRandom) {
68 if err := hs.sendDummyChangeCipherSpec(); err != nil {
71 if err := hs.processHelloRetryRequest(); err != nil {
76 hs.transcript.Write(hs.serverHello.marshal())
79 if err := hs.processServerHello(); err != nil {
82 if err := hs.sendDummyChangeCipherSpec(); err != nil {
85 if err := hs.establishHandshakeKeys(); err != nil {
88 if err := hs.readServerParameters(); err != nil {
91 if err := hs.readServerCertificate(); err != nil {
94 if err := hs.readServerFinished(); err != nil {
97 if err := hs.sendClientCertificate(); err != nil {
100 if err := hs.sendClientFinished(); err != nil {
103 if _, err := c.flush(); err != nil {
107 atomic.StoreUint32(&c.handshakeStatus, 1)
112 // checkServerHelloOrHRR does validity checks that apply to both ServerHello and
113 // HelloRetryRequest messages. It sets hs.suite.
114 func (hs *clientHandshakeStateTLS13) checkServerHelloOrHRR() error {
117 if hs.serverHello.supportedVersion == 0 {
118 c.sendAlert(alertMissingExtension)
119 return errors.New("tls: server selected TLS 1.3 using the legacy version field")
122 if hs.serverHello.supportedVersion != VersionTLS13 {
123 c.sendAlert(alertIllegalParameter)
124 return errors.New("tls: server selected an invalid version after a HelloRetryRequest")
127 if hs.serverHello.vers != VersionTLS12 {
128 c.sendAlert(alertIllegalParameter)
129 return errors.New("tls: server sent an incorrect legacy version")
132 if hs.serverHello.ocspStapling ||
133 hs.serverHello.ticketSupported ||
134 hs.serverHello.secureRenegotiationSupported ||
135 len(hs.serverHello.secureRenegotiation) != 0 ||
136 len(hs.serverHello.alpnProtocol) != 0 ||
137 len(hs.serverHello.scts) != 0 {
138 c.sendAlert(alertUnsupportedExtension)
139 return errors.New("tls: server sent a ServerHello extension forbidden in TLS 1.3")
142 if !bytes.Equal(hs.hello.sessionId, hs.serverHello.sessionId) {
143 c.sendAlert(alertIllegalParameter)
144 return errors.New("tls: server did not echo the legacy session ID")
147 if hs.serverHello.compressionMethod != compressionNone {
148 c.sendAlert(alertIllegalParameter)
149 return errors.New("tls: server selected unsupported compression format")
152 selectedSuite := mutualCipherSuiteTLS13(hs.hello.cipherSuites, hs.serverHello.cipherSuite)
153 if hs.suite != nil && selectedSuite != hs.suite {
154 c.sendAlert(alertIllegalParameter)
155 return errors.New("tls: server changed cipher suite after a HelloRetryRequest")
157 if selectedSuite == nil {
158 c.sendAlert(alertIllegalParameter)
159 return errors.New("tls: server chose an unconfigured cipher suite")
161 hs.suite = selectedSuite
162 c.cipherSuite = hs.suite.id
167 // sendDummyChangeCipherSpec sends a ChangeCipherSpec record for compatibility
168 // with middleboxes that didn't implement TLS correctly. See RFC 8446, Appendix D.4.
169 func (hs *clientHandshakeStateTLS13) sendDummyChangeCipherSpec() error {
173 hs.sentDummyCCS = true
175 _, err := hs.c.writeRecord(recordTypeChangeCipherSpec, []byte{1})
179 // processHelloRetryRequest handles the HRR in hs.serverHello, modifies and
180 // resends hs.hello, and reads the new ServerHello into hs.serverHello.
181 func (hs *clientHandshakeStateTLS13) processHelloRetryRequest() error {
184 // The first ClientHello gets double-hashed into the transcript upon a
185 // HelloRetryRequest. (The idea is that the server might offload transcript
186 // storage to the client in the cookie.) See RFC 8446, Section 4.4.1.
187 chHash := hs.transcript.Sum(nil)
188 hs.transcript.Reset()
189 hs.transcript.Write([]byte{typeMessageHash, 0, 0, uint8(len(chHash))})
190 hs.transcript.Write(chHash)
191 hs.transcript.Write(hs.serverHello.marshal())
193 // The only HelloRetryRequest extensions we support are key_share and
194 // cookie, and clients must abort the handshake if the HRR would not result
195 // in any change in the ClientHello.
196 if hs.serverHello.selectedGroup == 0 && hs.serverHello.cookie == nil {
197 c.sendAlert(alertIllegalParameter)
198 return errors.New("tls: server sent an unnecessary HelloRetryRequest message")
201 if hs.serverHello.cookie != nil {
202 hs.hello.cookie = hs.serverHello.cookie
205 if hs.serverHello.serverShare.group != 0 {
206 c.sendAlert(alertDecodeError)
207 return errors.New("tls: received malformed key_share extension")
210 // If the server sent a key_share extension selecting a group, ensure it's
211 // a group we advertised but did not send a key share for, and send a key
212 // share for it this time.
213 if curveID := hs.serverHello.selectedGroup; curveID != 0 {
215 for _, id := range hs.hello.supportedCurves {
222 c.sendAlert(alertIllegalParameter)
223 return errors.New("tls: server selected unsupported group")
225 if hs.ecdheParams.CurveID() == curveID {
226 c.sendAlert(alertIllegalParameter)
227 return errors.New("tls: server sent an unnecessary HelloRetryRequest key_share")
229 if _, ok := curveForCurveID(curveID); curveID != X25519 && !ok {
230 c.sendAlert(alertInternalError)
231 return errors.New("tls: CurvePreferences includes unsupported curve")
233 params, err := generateECDHEParameters(c.config.rand(), curveID)
235 c.sendAlert(alertInternalError)
238 hs.ecdheParams = params
239 hs.hello.keyShares = []keyShare{{group: curveID, data: params.PublicKey()}}
243 if len(hs.hello.pskIdentities) > 0 {
244 pskSuite := cipherSuiteTLS13ByID(hs.session.cipherSuite)
246 return c.sendAlert(alertInternalError)
248 if pskSuite.hash == hs.suite.hash {
249 // Update binders and obfuscated_ticket_age.
250 ticketAge := uint32(c.config.time().Sub(hs.session.receivedAt) / time.Millisecond)
251 hs.hello.pskIdentities[0].obfuscatedTicketAge = ticketAge + hs.session.ageAdd
253 transcript := hs.suite.hash.New()
254 transcript.Write([]byte{typeMessageHash, 0, 0, uint8(len(chHash))})
255 transcript.Write(chHash)
256 transcript.Write(hs.serverHello.marshal())
257 transcript.Write(hs.hello.marshalWithoutBinders())
258 pskBinders := [][]byte{hs.suite.finishedHash(hs.binderKey, transcript)}
259 hs.hello.updateBinders(pskBinders)
261 // Server selected a cipher suite incompatible with the PSK.
262 hs.hello.pskIdentities = nil
263 hs.hello.pskBinders = nil
267 hs.transcript.Write(hs.hello.marshal())
268 if _, err := c.writeRecord(recordTypeHandshake, hs.hello.marshal()); err != nil {
272 msg, err := c.readHandshake()
277 serverHello, ok := msg.(*serverHelloMsg)
279 c.sendAlert(alertUnexpectedMessage)
280 return unexpectedMessageError(serverHello, msg)
282 hs.serverHello = serverHello
284 if err := hs.checkServerHelloOrHRR(); err != nil {
291 func (hs *clientHandshakeStateTLS13) processServerHello() error {
294 if bytes.Equal(hs.serverHello.random, helloRetryRequestRandom) {
295 c.sendAlert(alertUnexpectedMessage)
296 return errors.New("tls: server sent two HelloRetryRequest messages")
299 if len(hs.serverHello.cookie) != 0 {
300 c.sendAlert(alertUnsupportedExtension)
301 return errors.New("tls: server sent a cookie in a normal ServerHello")
304 if hs.serverHello.selectedGroup != 0 {
305 c.sendAlert(alertDecodeError)
306 return errors.New("tls: malformed key_share extension")
309 if hs.serverHello.serverShare.group == 0 {
310 c.sendAlert(alertIllegalParameter)
311 return errors.New("tls: server did not send a key share")
313 if hs.serverHello.serverShare.group != hs.ecdheParams.CurveID() {
314 c.sendAlert(alertIllegalParameter)
315 return errors.New("tls: server selected unsupported group")
318 if !hs.serverHello.selectedIdentityPresent {
322 if int(hs.serverHello.selectedIdentity) >= len(hs.hello.pskIdentities) {
323 c.sendAlert(alertIllegalParameter)
324 return errors.New("tls: server selected an invalid PSK")
327 if len(hs.hello.pskIdentities) != 1 || hs.session == nil {
328 return c.sendAlert(alertInternalError)
330 pskSuite := cipherSuiteTLS13ByID(hs.session.cipherSuite)
332 return c.sendAlert(alertInternalError)
334 if pskSuite.hash != hs.suite.hash {
335 c.sendAlert(alertIllegalParameter)
336 return errors.New("tls: server selected an invalid PSK and cipher suite pair")
341 c.peerCertificates = hs.session.serverCertificates
342 c.verifiedChains = hs.session.verifiedChains
343 c.ocspResponse = hs.session.ocspResponse
344 c.scts = hs.session.scts
348 func (hs *clientHandshakeStateTLS13) establishHandshakeKeys() error {
351 sharedKey := hs.ecdheParams.SharedKey(hs.serverHello.serverShare.data)
352 if sharedKey == nil {
353 c.sendAlert(alertIllegalParameter)
354 return errors.New("tls: invalid server key share")
357 earlySecret := hs.earlySecret
359 earlySecret = hs.suite.extract(nil, nil)
361 handshakeSecret := hs.suite.extract(sharedKey,
362 hs.suite.deriveSecret(earlySecret, "derived", nil))
364 clientSecret := hs.suite.deriveSecret(handshakeSecret,
365 clientHandshakeTrafficLabel, hs.transcript)
366 c.out.setTrafficSecret(hs.suite, clientSecret)
367 serverSecret := hs.suite.deriveSecret(handshakeSecret,
368 serverHandshakeTrafficLabel, hs.transcript)
369 c.in.setTrafficSecret(hs.suite, serverSecret)
371 err := c.config.writeKeyLog(keyLogLabelClientHandshake, hs.hello.random, clientSecret)
373 c.sendAlert(alertInternalError)
376 err = c.config.writeKeyLog(keyLogLabelServerHandshake, hs.hello.random, serverSecret)
378 c.sendAlert(alertInternalError)
382 hs.masterSecret = hs.suite.extract(nil,
383 hs.suite.deriveSecret(handshakeSecret, "derived", nil))
388 func (hs *clientHandshakeStateTLS13) readServerParameters() error {
391 msg, err := c.readHandshake()
396 encryptedExtensions, ok := msg.(*encryptedExtensionsMsg)
398 c.sendAlert(alertUnexpectedMessage)
399 return unexpectedMessageError(encryptedExtensions, msg)
401 hs.transcript.Write(encryptedExtensions.marshal())
403 if err := checkALPN(hs.hello.alpnProtocols, encryptedExtensions.alpnProtocol); err != nil {
404 c.sendAlert(alertUnsupportedExtension)
407 c.clientProtocol = encryptedExtensions.alpnProtocol
412 func (hs *clientHandshakeStateTLS13) readServerCertificate() error {
415 // Either a PSK or a certificate is always used, but not both.
416 // See RFC 8446, Section 4.1.1.
418 // Make sure the connection is still being verified whether or not this
419 // is a resumption. Resumptions currently don't reverify certificates so
420 // they don't call verifyServerCertificate. See Issue 31641.
421 if c.config.VerifyConnection != nil {
422 if err := c.config.VerifyConnection(c.connectionStateLocked()); err != nil {
423 c.sendAlert(alertBadCertificate)
430 msg, err := c.readHandshake()
435 certReq, ok := msg.(*certificateRequestMsgTLS13)
437 hs.transcript.Write(certReq.marshal())
441 msg, err = c.readHandshake()
447 certMsg, ok := msg.(*certificateMsgTLS13)
449 c.sendAlert(alertUnexpectedMessage)
450 return unexpectedMessageError(certMsg, msg)
452 if len(certMsg.certificate.Certificate) == 0 {
453 c.sendAlert(alertDecodeError)
454 return errors.New("tls: received empty certificates message")
456 hs.transcript.Write(certMsg.marshal())
458 c.scts = certMsg.certificate.SignedCertificateTimestamps
459 c.ocspResponse = certMsg.certificate.OCSPStaple
461 if err := c.verifyServerCertificate(certMsg.certificate.Certificate); err != nil {
465 msg, err = c.readHandshake()
470 certVerify, ok := msg.(*certificateVerifyMsg)
472 c.sendAlert(alertUnexpectedMessage)
473 return unexpectedMessageError(certVerify, msg)
476 // See RFC 8446, Section 4.4.3.
477 if !isSupportedSignatureAlgorithm(certVerify.signatureAlgorithm, supportedSignatureAlgorithms()) {
478 c.sendAlert(alertIllegalParameter)
479 return errors.New("tls: certificate used with invalid signature algorithm")
481 sigType, sigHash, err := typeAndHashFromSignatureScheme(certVerify.signatureAlgorithm)
483 return c.sendAlert(alertInternalError)
485 if sigType == signaturePKCS1v15 || sigHash == crypto.SHA1 {
486 c.sendAlert(alertIllegalParameter)
487 return errors.New("tls: certificate used with invalid signature algorithm")
489 signed := signedMessage(sigHash, serverSignatureContext, hs.transcript)
490 if err := verifyHandshakeSignature(sigType, c.peerCertificates[0].PublicKey,
491 sigHash, signed, certVerify.signature); err != nil {
492 c.sendAlert(alertDecryptError)
493 return errors.New("tls: invalid signature by the server certificate: " + err.Error())
496 hs.transcript.Write(certVerify.marshal())
501 func (hs *clientHandshakeStateTLS13) readServerFinished() error {
504 msg, err := c.readHandshake()
509 finished, ok := msg.(*finishedMsg)
511 c.sendAlert(alertUnexpectedMessage)
512 return unexpectedMessageError(finished, msg)
515 expectedMAC := hs.suite.finishedHash(c.in.trafficSecret, hs.transcript)
516 if !hmac.Equal(expectedMAC, finished.verifyData) {
517 c.sendAlert(alertDecryptError)
518 return errors.New("tls: invalid server finished hash")
521 hs.transcript.Write(finished.marshal())
523 // Derive secrets that take context through the server Finished.
525 hs.trafficSecret = hs.suite.deriveSecret(hs.masterSecret,
526 clientApplicationTrafficLabel, hs.transcript)
527 serverSecret := hs.suite.deriveSecret(hs.masterSecret,
528 serverApplicationTrafficLabel, hs.transcript)
529 c.in.setTrafficSecret(hs.suite, serverSecret)
531 err = c.config.writeKeyLog(keyLogLabelClientTraffic, hs.hello.random, hs.trafficSecret)
533 c.sendAlert(alertInternalError)
536 err = c.config.writeKeyLog(keyLogLabelServerTraffic, hs.hello.random, serverSecret)
538 c.sendAlert(alertInternalError)
542 c.ekm = hs.suite.exportKeyingMaterial(hs.masterSecret, hs.transcript)
547 func (hs *clientHandshakeStateTLS13) sendClientCertificate() error {
550 if hs.certReq == nil {
554 cert, err := c.getClientCertificate(&CertificateRequestInfo{
555 AcceptableCAs: hs.certReq.certificateAuthorities,
556 SignatureSchemes: hs.certReq.supportedSignatureAlgorithms,
564 certMsg := new(certificateMsgTLS13)
566 certMsg.certificate = *cert
567 certMsg.scts = hs.certReq.scts && len(cert.SignedCertificateTimestamps) > 0
568 certMsg.ocspStapling = hs.certReq.ocspStapling && len(cert.OCSPStaple) > 0
570 hs.transcript.Write(certMsg.marshal())
571 if _, err := c.writeRecord(recordTypeHandshake, certMsg.marshal()); err != nil {
575 // If we sent an empty certificate message, skip the CertificateVerify.
576 if len(cert.Certificate) == 0 {
580 certVerifyMsg := new(certificateVerifyMsg)
581 certVerifyMsg.hasSignatureAlgorithm = true
583 certVerifyMsg.signatureAlgorithm, err = selectSignatureScheme(c.vers, cert, hs.certReq.supportedSignatureAlgorithms)
585 // getClientCertificate returned a certificate incompatible with the
586 // CertificateRequestInfo supported signature algorithms.
587 c.sendAlert(alertHandshakeFailure)
591 sigType, sigHash, err := typeAndHashFromSignatureScheme(certVerifyMsg.signatureAlgorithm)
593 return c.sendAlert(alertInternalError)
596 signed := signedMessage(sigHash, clientSignatureContext, hs.transcript)
597 signOpts := crypto.SignerOpts(sigHash)
598 if sigType == signatureRSAPSS {
599 signOpts = &rsa.PSSOptions{SaltLength: rsa.PSSSaltLengthEqualsHash, Hash: sigHash}
601 sig, err := cert.PrivateKey.(crypto.Signer).Sign(c.config.rand(), signed, signOpts)
603 c.sendAlert(alertInternalError)
604 return errors.New("tls: failed to sign handshake: " + err.Error())
606 certVerifyMsg.signature = sig
608 hs.transcript.Write(certVerifyMsg.marshal())
609 if _, err := c.writeRecord(recordTypeHandshake, certVerifyMsg.marshal()); err != nil {
616 func (hs *clientHandshakeStateTLS13) sendClientFinished() error {
619 finished := &finishedMsg{
620 verifyData: hs.suite.finishedHash(c.out.trafficSecret, hs.transcript),
623 hs.transcript.Write(finished.marshal())
624 if _, err := c.writeRecord(recordTypeHandshake, finished.marshal()); err != nil {
628 c.out.setTrafficSecret(hs.suite, hs.trafficSecret)
630 if !c.config.SessionTicketsDisabled && c.config.ClientSessionCache != nil {
631 c.resumptionSecret = hs.suite.deriveSecret(hs.masterSecret,
632 resumptionLabel, hs.transcript)
638 func (c *Conn) handleNewSessionTicket(msg *newSessionTicketMsgTLS13) error {
640 c.sendAlert(alertUnexpectedMessage)
641 return errors.New("tls: received new session ticket from a client")
644 if c.config.SessionTicketsDisabled || c.config.ClientSessionCache == nil {
648 // See RFC 8446, Section 4.6.1.
649 if msg.lifetime == 0 {
652 lifetime := time.Duration(msg.lifetime) * time.Second
653 if lifetime > maxSessionTicketLifetime {
654 c.sendAlert(alertIllegalParameter)
655 return errors.New("tls: received a session ticket with invalid lifetime")
658 cipherSuite := cipherSuiteTLS13ByID(c.cipherSuite)
659 if cipherSuite == nil || c.resumptionSecret == nil {
660 return c.sendAlert(alertInternalError)
663 // Save the resumption_master_secret and nonce instead of deriving the PSK
664 // to do the least amount of work on NewSessionTicket messages before we
665 // know if the ticket will be used. Forward secrecy of resumed connections
666 // is guaranteed by the requirement for pskModeDHE.
667 session := &ClientSessionState{
668 sessionTicket: msg.label,
670 cipherSuite: c.cipherSuite,
671 masterSecret: c.resumptionSecret,
672 serverCertificates: c.peerCertificates,
673 verifiedChains: c.verifiedChains,
674 receivedAt: c.config.time(),
676 useBy: c.config.time().Add(lifetime),
678 ocspResponse: c.ocspResponse,
682 cacheKey := clientSessionCacheKey(c.conn.RemoteAddr(), c.config)
683 c.config.ClientSessionCache.Put(cacheKey, session)