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.
18 type clientHandshakeStateTLS13 struct {
20 serverHello *serverHelloMsg
22 ecdheParams ecdheParameters
24 session *ClientSessionState
28 certReq *certificateRequestMsgTLS13
31 suite *cipherSuiteTLS13
34 trafficSecret []byte // client_application_traffic_secret_0
37 // handshake requires hs.c, hs.hello, hs.serverHello, hs.ecdheParams, and,
38 // optionally, hs.session, hs.earlySecret and hs.binderKey to be set.
39 func (hs *clientHandshakeStateTLS13) handshake() error {
43 return errors.New("tls: internal error: TLS 1.3 reached in FIPS mode")
46 // The server must not select TLS 1.3 in a renegotiation. See RFC 8446,
47 // sections 4.1.2 and 4.1.3.
49 c.sendAlert(alertProtocolVersion)
50 return errors.New("tls: server selected TLS 1.3 in a renegotiation")
53 // Consistency check on the presence of a keyShare and its parameters.
54 if hs.ecdheParams == nil || len(hs.hello.keyShares) != 1 {
55 return c.sendAlert(alertInternalError)
58 if err := hs.checkServerHelloOrHRR(); err != nil {
62 hs.transcript = hs.suite.hash.New()
63 hs.transcript.Write(hs.hello.marshal())
65 if bytes.Equal(hs.serverHello.random, helloRetryRequestRandom) {
66 if err := hs.sendDummyChangeCipherSpec(); err != nil {
69 if err := hs.processHelloRetryRequest(); err != nil {
74 hs.transcript.Write(hs.serverHello.marshal())
77 if err := hs.processServerHello(); err != nil {
80 if err := hs.sendDummyChangeCipherSpec(); err != nil {
83 if err := hs.establishHandshakeKeys(); err != nil {
86 if err := hs.readServerParameters(); err != nil {
89 if err := hs.readServerCertificate(); err != nil {
92 if err := hs.readServerFinished(); err != nil {
95 if err := hs.sendClientCertificate(); err != nil {
98 if err := hs.sendClientFinished(); err != nil {
101 if _, err := c.flush(); err != nil {
105 atomic.StoreUint32(&c.handshakeStatus, 1)
110 // checkServerHelloOrHRR does validity checks that apply to both ServerHello and
111 // HelloRetryRequest messages. It sets hs.suite.
112 func (hs *clientHandshakeStateTLS13) checkServerHelloOrHRR() error {
115 if hs.serverHello.supportedVersion == 0 {
116 c.sendAlert(alertMissingExtension)
117 return errors.New("tls: server selected TLS 1.3 using the legacy version field")
120 if hs.serverHello.supportedVersion != VersionTLS13 {
121 c.sendAlert(alertIllegalParameter)
122 return errors.New("tls: server selected an invalid version after a HelloRetryRequest")
125 if hs.serverHello.vers != VersionTLS12 {
126 c.sendAlert(alertIllegalParameter)
127 return errors.New("tls: server sent an incorrect legacy version")
130 if hs.serverHello.ocspStapling ||
131 hs.serverHello.ticketSupported ||
132 hs.serverHello.secureRenegotiationSupported ||
133 len(hs.serverHello.secureRenegotiation) != 0 ||
134 len(hs.serverHello.alpnProtocol) != 0 ||
135 len(hs.serverHello.scts) != 0 {
136 c.sendAlert(alertUnsupportedExtension)
137 return errors.New("tls: server sent a ServerHello extension forbidden in TLS 1.3")
140 if !bytes.Equal(hs.hello.sessionId, hs.serverHello.sessionId) {
141 c.sendAlert(alertIllegalParameter)
142 return errors.New("tls: server did not echo the legacy session ID")
145 if hs.serverHello.compressionMethod != compressionNone {
146 c.sendAlert(alertIllegalParameter)
147 return errors.New("tls: server selected unsupported compression format")
150 selectedSuite := mutualCipherSuiteTLS13(hs.hello.cipherSuites, hs.serverHello.cipherSuite)
151 if hs.suite != nil && selectedSuite != hs.suite {
152 c.sendAlert(alertIllegalParameter)
153 return errors.New("tls: server changed cipher suite after a HelloRetryRequest")
155 if selectedSuite == nil {
156 c.sendAlert(alertIllegalParameter)
157 return errors.New("tls: server chose an unconfigured cipher suite")
159 hs.suite = selectedSuite
160 c.cipherSuite = hs.suite.id
165 // sendDummyChangeCipherSpec sends a ChangeCipherSpec record for compatibility
166 // with middleboxes that didn't implement TLS correctly. See RFC 8446, Appendix D.4.
167 func (hs *clientHandshakeStateTLS13) sendDummyChangeCipherSpec() error {
171 hs.sentDummyCCS = true
173 _, err := hs.c.writeRecord(recordTypeChangeCipherSpec, []byte{1})
177 // processHelloRetryRequest handles the HRR in hs.serverHello, modifies and
178 // resends hs.hello, and reads the new ServerHello into hs.serverHello.
179 func (hs *clientHandshakeStateTLS13) processHelloRetryRequest() error {
182 // The first ClientHello gets double-hashed into the transcript upon a
183 // HelloRetryRequest. See RFC 8446, Section 4.4.1.
184 chHash := hs.transcript.Sum(nil)
185 hs.transcript.Reset()
186 hs.transcript.Write([]byte{typeMessageHash, 0, 0, uint8(len(chHash))})
187 hs.transcript.Write(chHash)
188 hs.transcript.Write(hs.serverHello.marshal())
190 if hs.serverHello.serverShare.group != 0 {
191 c.sendAlert(alertDecodeError)
192 return errors.New("tls: received malformed key_share extension")
195 curveID := hs.serverHello.selectedGroup
197 c.sendAlert(alertMissingExtension)
198 return errors.New("tls: received HelloRetryRequest without selected group")
201 for _, id := range hs.hello.supportedCurves {
208 c.sendAlert(alertIllegalParameter)
209 return errors.New("tls: server selected unsupported group")
211 if hs.ecdheParams.CurveID() == curveID {
212 c.sendAlert(alertIllegalParameter)
213 return errors.New("tls: server sent an unnecessary HelloRetryRequest message")
215 if _, ok := curveForCurveID(curveID); curveID != X25519 && !ok {
216 c.sendAlert(alertInternalError)
217 return errors.New("tls: CurvePreferences includes unsupported curve")
219 params, err := generateECDHEParameters(c.config.rand(), curveID)
221 c.sendAlert(alertInternalError)
224 hs.ecdheParams = params
225 hs.hello.keyShares = []keyShare{{group: curveID, data: params.PublicKey()}}
227 hs.hello.cookie = hs.serverHello.cookie
230 if len(hs.hello.pskIdentities) > 0 {
231 pskSuite := cipherSuiteTLS13ByID(hs.session.cipherSuite)
233 return c.sendAlert(alertInternalError)
235 if pskSuite.hash == hs.suite.hash {
236 // Update binders and obfuscated_ticket_age.
237 ticketAge := uint32(c.config.time().Sub(hs.session.receivedAt) / time.Millisecond)
238 hs.hello.pskIdentities[0].obfuscatedTicketAge = ticketAge + hs.session.ageAdd
240 transcript := hs.suite.hash.New()
241 transcript.Write([]byte{typeMessageHash, 0, 0, uint8(len(chHash))})
242 transcript.Write(chHash)
243 transcript.Write(hs.serverHello.marshal())
244 transcript.Write(hs.hello.marshalWithoutBinders())
245 pskBinders := [][]byte{hs.suite.finishedHash(hs.binderKey, transcript)}
246 hs.hello.updateBinders(pskBinders)
248 // Server selected a cipher suite incompatible with the PSK.
249 hs.hello.pskIdentities = nil
250 hs.hello.pskBinders = nil
254 hs.transcript.Write(hs.hello.marshal())
255 if _, err := c.writeRecord(recordTypeHandshake, hs.hello.marshal()); err != nil {
259 msg, err := c.readHandshake()
264 serverHello, ok := msg.(*serverHelloMsg)
266 c.sendAlert(alertUnexpectedMessage)
267 return unexpectedMessageError(serverHello, msg)
269 hs.serverHello = serverHello
271 if err := hs.checkServerHelloOrHRR(); err != nil {
278 func (hs *clientHandshakeStateTLS13) processServerHello() error {
281 if bytes.Equal(hs.serverHello.random, helloRetryRequestRandom) {
282 c.sendAlert(alertUnexpectedMessage)
283 return errors.New("tls: server sent two HelloRetryRequest messages")
286 if len(hs.serverHello.cookie) != 0 {
287 c.sendAlert(alertUnsupportedExtension)
288 return errors.New("tls: server sent a cookie in a normal ServerHello")
291 if hs.serverHello.selectedGroup != 0 {
292 c.sendAlert(alertDecodeError)
293 return errors.New("tls: malformed key_share extension")
296 if hs.serverHello.serverShare.group == 0 {
297 c.sendAlert(alertIllegalParameter)
298 return errors.New("tls: server did not send a key share")
300 if hs.serverHello.serverShare.group != hs.ecdheParams.CurveID() {
301 c.sendAlert(alertIllegalParameter)
302 return errors.New("tls: server selected unsupported group")
305 if !hs.serverHello.selectedIdentityPresent {
309 if int(hs.serverHello.selectedIdentity) >= len(hs.hello.pskIdentities) {
310 c.sendAlert(alertIllegalParameter)
311 return errors.New("tls: server selected an invalid PSK")
314 if len(hs.hello.pskIdentities) != 1 || hs.session == nil {
315 return c.sendAlert(alertInternalError)
317 pskSuite := cipherSuiteTLS13ByID(hs.session.cipherSuite)
319 return c.sendAlert(alertInternalError)
321 if pskSuite.hash != hs.suite.hash {
322 c.sendAlert(alertIllegalParameter)
323 return errors.New("tls: server selected an invalid PSK and cipher suite pair")
328 c.peerCertificates = hs.session.serverCertificates
329 c.verifiedChains = hs.session.verifiedChains
333 func (hs *clientHandshakeStateTLS13) establishHandshakeKeys() error {
336 sharedKey := hs.ecdheParams.SharedKey(hs.serverHello.serverShare.data)
337 if sharedKey == nil {
338 c.sendAlert(alertIllegalParameter)
339 return errors.New("tls: invalid server key share")
342 earlySecret := hs.earlySecret
344 earlySecret = hs.suite.extract(nil, nil)
346 handshakeSecret := hs.suite.extract(sharedKey,
347 hs.suite.deriveSecret(earlySecret, "derived", nil))
349 clientSecret := hs.suite.deriveSecret(handshakeSecret,
350 clientHandshakeTrafficLabel, hs.transcript)
351 c.out.setTrafficSecret(hs.suite, clientSecret)
352 serverSecret := hs.suite.deriveSecret(handshakeSecret,
353 serverHandshakeTrafficLabel, hs.transcript)
354 c.in.setTrafficSecret(hs.suite, serverSecret)
356 err := c.config.writeKeyLog(keyLogLabelClientHandshake, hs.hello.random, clientSecret)
358 c.sendAlert(alertInternalError)
361 err = c.config.writeKeyLog(keyLogLabelServerHandshake, hs.hello.random, serverSecret)
363 c.sendAlert(alertInternalError)
367 hs.masterSecret = hs.suite.extract(nil,
368 hs.suite.deriveSecret(handshakeSecret, "derived", nil))
373 func (hs *clientHandshakeStateTLS13) readServerParameters() error {
376 msg, err := c.readHandshake()
381 encryptedExtensions, ok := msg.(*encryptedExtensionsMsg)
383 c.sendAlert(alertUnexpectedMessage)
384 return unexpectedMessageError(encryptedExtensions, msg)
386 hs.transcript.Write(encryptedExtensions.marshal())
388 if len(encryptedExtensions.alpnProtocol) != 0 && len(hs.hello.alpnProtocols) == 0 {
389 c.sendAlert(alertUnsupportedExtension)
390 return errors.New("tls: server advertised unrequested ALPN extension")
392 c.clientProtocol = encryptedExtensions.alpnProtocol
397 func (hs *clientHandshakeStateTLS13) readServerCertificate() error {
400 // Either a PSK or a certificate is always used, but not both.
401 // See RFC 8446, Section 4.1.1.
406 msg, err := c.readHandshake()
411 certReq, ok := msg.(*certificateRequestMsgTLS13)
413 hs.transcript.Write(certReq.marshal())
417 msg, err = c.readHandshake()
423 certMsg, ok := msg.(*certificateMsgTLS13)
425 c.sendAlert(alertUnexpectedMessage)
426 return unexpectedMessageError(certMsg, msg)
428 if len(certMsg.certificate.Certificate) == 0 {
429 c.sendAlert(alertDecodeError)
430 return errors.New("tls: received empty certificates message")
432 hs.transcript.Write(certMsg.marshal())
434 c.scts = certMsg.certificate.SignedCertificateTimestamps
435 c.ocspResponse = certMsg.certificate.OCSPStaple
437 if err := c.verifyServerCertificate(certMsg.certificate.Certificate); err != nil {
441 msg, err = c.readHandshake()
446 certVerify, ok := msg.(*certificateVerifyMsg)
448 c.sendAlert(alertUnexpectedMessage)
449 return unexpectedMessageError(certVerify, msg)
452 // See RFC 8446, Section 4.4.3.
453 if !isSupportedSignatureAlgorithm(certVerify.signatureAlgorithm, supportedSignatureAlgorithms()) {
454 c.sendAlert(alertIllegalParameter)
455 return errors.New("tls: certificate used with invalid signature algorithm")
457 sigType, sigHash, err := typeAndHashFromSignatureScheme(certVerify.signatureAlgorithm)
459 return c.sendAlert(alertInternalError)
461 if sigType == signaturePKCS1v15 || sigHash == crypto.SHA1 {
462 c.sendAlert(alertIllegalParameter)
463 return errors.New("tls: certificate used with invalid signature algorithm")
465 signed := signedMessage(sigHash, serverSignatureContext, hs.transcript)
466 if err := verifyHandshakeSignature(sigType, c.peerCertificates[0].PublicKey,
467 sigHash, signed, certVerify.signature); err != nil {
468 c.sendAlert(alertDecryptError)
469 return errors.New("tls: invalid signature by the server certificate: " + err.Error())
472 hs.transcript.Write(certVerify.marshal())
477 func (hs *clientHandshakeStateTLS13) readServerFinished() error {
480 msg, err := c.readHandshake()
485 finished, ok := msg.(*finishedMsg)
487 c.sendAlert(alertUnexpectedMessage)
488 return unexpectedMessageError(finished, msg)
491 expectedMAC := hs.suite.finishedHash(c.in.trafficSecret, hs.transcript)
492 if !hmac.Equal(expectedMAC, finished.verifyData) {
493 c.sendAlert(alertDecryptError)
494 return errors.New("tls: invalid server finished hash")
497 hs.transcript.Write(finished.marshal())
499 // Derive secrets that take context through the server Finished.
501 hs.trafficSecret = hs.suite.deriveSecret(hs.masterSecret,
502 clientApplicationTrafficLabel, hs.transcript)
503 serverSecret := hs.suite.deriveSecret(hs.masterSecret,
504 serverApplicationTrafficLabel, hs.transcript)
505 c.in.setTrafficSecret(hs.suite, serverSecret)
507 err = c.config.writeKeyLog(keyLogLabelClientTraffic, hs.hello.random, hs.trafficSecret)
509 c.sendAlert(alertInternalError)
512 err = c.config.writeKeyLog(keyLogLabelServerTraffic, hs.hello.random, serverSecret)
514 c.sendAlert(alertInternalError)
518 c.ekm = hs.suite.exportKeyingMaterial(hs.masterSecret, hs.transcript)
523 func (hs *clientHandshakeStateTLS13) sendClientCertificate() error {
526 if hs.certReq == nil {
530 cert, err := c.getClientCertificate(&CertificateRequestInfo{
531 AcceptableCAs: hs.certReq.certificateAuthorities,
532 SignatureSchemes: hs.certReq.supportedSignatureAlgorithms,
538 certMsg := new(certificateMsgTLS13)
540 certMsg.certificate = *cert
541 certMsg.scts = hs.certReq.scts && len(cert.SignedCertificateTimestamps) > 0
542 certMsg.ocspStapling = hs.certReq.ocspStapling && len(cert.OCSPStaple) > 0
544 hs.transcript.Write(certMsg.marshal())
545 if _, err := c.writeRecord(recordTypeHandshake, certMsg.marshal()); err != nil {
549 // If we sent an empty certificate message, skip the CertificateVerify.
550 if len(cert.Certificate) == 0 {
554 certVerifyMsg := new(certificateVerifyMsg)
555 certVerifyMsg.hasSignatureAlgorithm = true
557 certVerifyMsg.signatureAlgorithm, err = selectSignatureScheme(c.vers, cert, hs.certReq.supportedSignatureAlgorithms)
559 // getClientCertificate returned a certificate incompatible with the
560 // CertificateRequestInfo supported signature algorithms.
561 c.sendAlert(alertHandshakeFailure)
565 sigType, sigHash, err := typeAndHashFromSignatureScheme(certVerifyMsg.signatureAlgorithm)
567 return c.sendAlert(alertInternalError)
570 signed := signedMessage(sigHash, clientSignatureContext, hs.transcript)
571 signOpts := crypto.SignerOpts(sigHash)
572 if sigType == signatureRSAPSS {
573 signOpts = &rsa.PSSOptions{SaltLength: rsa.PSSSaltLengthEqualsHash, Hash: sigHash}
575 sig, err := cert.PrivateKey.(crypto.Signer).Sign(c.config.rand(), signed, signOpts)
577 c.sendAlert(alertInternalError)
578 return errors.New("tls: failed to sign handshake: " + err.Error())
580 certVerifyMsg.signature = sig
582 hs.transcript.Write(certVerifyMsg.marshal())
583 if _, err := c.writeRecord(recordTypeHandshake, certVerifyMsg.marshal()); err != nil {
590 func (hs *clientHandshakeStateTLS13) sendClientFinished() error {
593 finished := &finishedMsg{
594 verifyData: hs.suite.finishedHash(c.out.trafficSecret, hs.transcript),
597 hs.transcript.Write(finished.marshal())
598 if _, err := c.writeRecord(recordTypeHandshake, finished.marshal()); err != nil {
602 c.out.setTrafficSecret(hs.suite, hs.trafficSecret)
604 if !c.config.SessionTicketsDisabled && c.config.ClientSessionCache != nil {
605 c.resumptionSecret = hs.suite.deriveSecret(hs.masterSecret,
606 resumptionLabel, hs.transcript)
612 func (c *Conn) handleNewSessionTicket(msg *newSessionTicketMsgTLS13) error {
614 c.sendAlert(alertUnexpectedMessage)
615 return errors.New("tls: received new session ticket from a client")
618 if c.config.SessionTicketsDisabled || c.config.ClientSessionCache == nil {
622 // See RFC 8446, Section 4.6.1.
623 if msg.lifetime == 0 {
626 lifetime := time.Duration(msg.lifetime) * time.Second
627 if lifetime > maxSessionTicketLifetime {
628 c.sendAlert(alertIllegalParameter)
629 return errors.New("tls: received a session ticket with invalid lifetime")
632 cipherSuite := cipherSuiteTLS13ByID(c.cipherSuite)
633 if cipherSuite == nil || c.resumptionSecret == nil {
634 return c.sendAlert(alertInternalError)
637 // Save the resumption_master_secret and nonce instead of deriving the PSK
638 // to do the least amount of work on NewSessionTicket messages before we
639 // know if the ticket will be used. Forward secrecy of resumed connections
640 // is guaranteed by the requirement for pskModeDHE.
641 session := &ClientSessionState{
642 sessionTicket: msg.label,
644 cipherSuite: c.cipherSuite,
645 masterSecret: c.resumptionSecret,
646 serverCertificates: c.peerCertificates,
647 verifiedChains: c.verifiedChains,
648 receivedAt: c.config.time(),
650 useBy: c.config.time().Add(lifetime),
654 cacheKey := clientSessionCacheKey(c.conn.RemoteAddr(), c.config)
655 c.config.ClientSessionCache.Put(cacheKey, session)