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.
4
5package qtls
6
7import (
8	"bytes"
9	"crypto"
10	"crypto/hmac"
11	"crypto/rsa"
12	"encoding/binary"
13	"errors"
14	"fmt"
15	"hash"
16	"sync/atomic"
17	"time"
18
19	"golang.org/x/crypto/cryptobyte"
20)
21
22type clientHandshakeStateTLS13 struct {
23	c           *Conn
24	serverHello *serverHelloMsg
25	hello       *clientHelloMsg
26	ecdheParams ecdheParameters
27
28	session     *clientSessionState
29	earlySecret []byte
30	binderKey   []byte
31
32	certReq       *certificateRequestMsgTLS13
33	usingPSK      bool
34	sentDummyCCS  bool
35	suite         *cipherSuiteTLS13
36	transcript    hash.Hash
37	masterSecret  []byte
38	trafficSecret []byte // client_application_traffic_secret_0
39}
40
41// handshake requires hs.c, hs.hello, hs.serverHello, hs.ecdheParams, and,
42// optionally, hs.session, hs.earlySecret and hs.binderKey to be set.
43func (hs *clientHandshakeStateTLS13) handshake() error {
44	c := hs.c
45
46	// The server must not select TLS 1.3 in a renegotiation. See RFC 8446,
47	// sections 4.1.2 and 4.1.3.
48	if c.handshakes > 0 {
49		c.sendAlert(alertProtocolVersion)
50		return errors.New("tls: server selected TLS 1.3 in a renegotiation")
51	}
52
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)
56	}
57
58	if err := hs.checkServerHelloOrHRR(); err != nil {
59		return err
60	}
61
62	hs.transcript = hs.suite.hash.New()
63	hs.transcript.Write(hs.hello.marshal())
64
65	if bytes.Equal(hs.serverHello.random, helloRetryRequestRandom) {
66		if err := hs.sendDummyChangeCipherSpec(); err != nil {
67			return err
68		}
69		if err := hs.processHelloRetryRequest(); err != nil {
70			return err
71		}
72	}
73
74	hs.transcript.Write(hs.serverHello.marshal())
75
76	c.buffering = true
77	if err := hs.processServerHello(); err != nil {
78		return err
79	}
80	if err := hs.sendDummyChangeCipherSpec(); err != nil {
81		return err
82	}
83	if err := hs.establishHandshakeKeys(); err != nil {
84		return err
85	}
86	if err := hs.readServerParameters(); err != nil {
87		return err
88	}
89	if err := hs.readServerCertificate(); err != nil {
90		return err
91	}
92	if err := hs.readServerFinished(); err != nil {
93		return err
94	}
95	if err := hs.sendClientCertificate(); err != nil {
96		return err
97	}
98	if err := hs.sendClientFinished(); err != nil {
99		return err
100	}
101	if _, err := c.flush(); err != nil {
102		return err
103	}
104
105	atomic.StoreUint32(&c.handshakeStatus, 1)
106
107	return nil
108}
109
110// checkServerHelloOrHRR does validity checks that apply to both ServerHello and
111// HelloRetryRequest messages. It sets hs.suite.
112func (hs *clientHandshakeStateTLS13) checkServerHelloOrHRR() error {
113	c := hs.c
114
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")
118	}
119
120	if hs.serverHello.supportedVersion != VersionTLS13 {
121		c.sendAlert(alertIllegalParameter)
122		return errors.New("tls: server selected an invalid version after a HelloRetryRequest")
123	}
124
125	if hs.serverHello.vers != VersionTLS12 {
126		c.sendAlert(alertIllegalParameter)
127		return errors.New("tls: server sent an incorrect legacy version")
128	}
129
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")
138	}
139
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")
143	}
144
145	if hs.serverHello.compressionMethod != compressionNone {
146		c.sendAlert(alertIllegalParameter)
147		return errors.New("tls: server selected unsupported compression format")
148	}
149
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")
154	}
155	if selectedSuite == nil {
156		c.sendAlert(alertIllegalParameter)
157		return errors.New("tls: server chose an unconfigured cipher suite")
158	}
159	hs.suite = selectedSuite
160	c.cipherSuite = hs.suite.id
161
162	return nil
163}
164
165// sendDummyChangeCipherSpec sends a ChangeCipherSpec record for compatibility
166// with middleboxes that didn't implement TLS correctly. See RFC 8446, Appendix D.4.
167func (hs *clientHandshakeStateTLS13) sendDummyChangeCipherSpec() error {
168	if hs.sentDummyCCS {
169		return nil
170	}
171	hs.sentDummyCCS = true
172
173	_, err := hs.c.writeRecord(recordTypeChangeCipherSpec, []byte{1})
174	return err
175}
176
177// processHelloRetryRequest handles the HRR in hs.serverHello, modifies and
178// resends hs.hello, and reads the new ServerHello into hs.serverHello.
179func (hs *clientHandshakeStateTLS13) processHelloRetryRequest() error {
180	c := hs.c
181
182	// The first ClientHello gets double-hashed into the transcript upon a
183	// HelloRetryRequest. (The idea is that the server might offload transcript
184	// storage to the client in the cookie.) See RFC 8446, Section 4.4.1.
185	chHash := hs.transcript.Sum(nil)
186	hs.transcript.Reset()
187	hs.transcript.Write([]byte{typeMessageHash, 0, 0, uint8(len(chHash))})
188	hs.transcript.Write(chHash)
189	hs.transcript.Write(hs.serverHello.marshal())
190
191	// The only HelloRetryRequest extensions we support are key_share and
192	// cookie, and clients must abort the handshake if the HRR would not result
193	// in any change in the ClientHello.
194	if hs.serverHello.selectedGroup == 0 && hs.serverHello.cookie == nil {
195		c.sendAlert(alertIllegalParameter)
196		return errors.New("tls: server sent an unnecessary HelloRetryRequest message")
197	}
198
199	if hs.serverHello.cookie != nil {
200		hs.hello.cookie = hs.serverHello.cookie
201	}
202
203	if hs.serverHello.serverShare.group != 0 {
204		c.sendAlert(alertDecodeError)
205		return errors.New("tls: received malformed key_share extension")
206	}
207
208	// If the server sent a key_share extension selecting a group, ensure it's
209	// a group we advertised but did not send a key share for, and send a key
210	// share for it this time.
211	if curveID := hs.serverHello.selectedGroup; curveID != 0 {
212		curveOK := false
213		for _, id := range hs.hello.supportedCurves {
214			if id == curveID {
215				curveOK = true
216				break
217			}
218		}
219		if !curveOK {
220			c.sendAlert(alertIllegalParameter)
221			return errors.New("tls: server selected unsupported group")
222		}
223		if hs.ecdheParams.CurveID() == curveID {
224			c.sendAlert(alertIllegalParameter)
225			return errors.New("tls: server sent an unnecessary HelloRetryRequest key_share")
226		}
227		if _, ok := curveForCurveID(curveID); curveID != X25519 && !ok {
228			c.sendAlert(alertInternalError)
229			return errors.New("tls: CurvePreferences includes unsupported curve")
230		}
231		params, err := generateECDHEParameters(c.config.rand(), curveID)
232		if err != nil {
233			c.sendAlert(alertInternalError)
234			return err
235		}
236		hs.ecdheParams = params
237		hs.hello.keyShares = []keyShare{{group: curveID, data: params.PublicKey()}}
238	}
239
240	hs.hello.raw = nil
241	if len(hs.hello.pskIdentities) > 0 {
242		pskSuite := cipherSuiteTLS13ByID(hs.session.cipherSuite)
243		if pskSuite == nil {
244			return c.sendAlert(alertInternalError)
245		}
246		if pskSuite.hash == hs.suite.hash {
247			// Update binders and obfuscated_ticket_age.
248			ticketAge := uint32(c.config.time().Sub(hs.session.receivedAt) / time.Millisecond)
249			hs.hello.pskIdentities[0].obfuscatedTicketAge = ticketAge + hs.session.ageAdd
250
251			transcript := hs.suite.hash.New()
252			transcript.Write([]byte{typeMessageHash, 0, 0, uint8(len(chHash))})
253			transcript.Write(chHash)
254			transcript.Write(hs.serverHello.marshal())
255			transcript.Write(hs.hello.marshalWithoutBinders())
256			pskBinders := [][]byte{hs.suite.finishedHash(hs.binderKey, transcript)}
257			hs.hello.updateBinders(pskBinders)
258		} else {
259			// Server selected a cipher suite incompatible with the PSK.
260			hs.hello.pskIdentities = nil
261			hs.hello.pskBinders = nil
262		}
263	}
264
265	if hs.hello.earlyData && c.extraConfig != nil && c.extraConfig.Rejected0RTT != nil {
266		c.extraConfig.Rejected0RTT()
267	}
268	hs.hello.earlyData = false // disable 0-RTT
269
270	hs.transcript.Write(hs.hello.marshal())
271	if _, err := c.writeRecord(recordTypeHandshake, hs.hello.marshal()); err != nil {
272		return err
273	}
274
275	msg, err := c.readHandshake()
276	if err != nil {
277		return err
278	}
279
280	serverHello, ok := msg.(*serverHelloMsg)
281	if !ok {
282		c.sendAlert(alertUnexpectedMessage)
283		return unexpectedMessageError(serverHello, msg)
284	}
285	hs.serverHello = serverHello
286
287	if err := hs.checkServerHelloOrHRR(); err != nil {
288		return err
289	}
290
291	return nil
292}
293
294func (hs *clientHandshakeStateTLS13) processServerHello() error {
295	c := hs.c
296
297	if bytes.Equal(hs.serverHello.random, helloRetryRequestRandom) {
298		c.sendAlert(alertUnexpectedMessage)
299		return errors.New("tls: server sent two HelloRetryRequest messages")
300	}
301
302	if len(hs.serverHello.cookie) != 0 {
303		c.sendAlert(alertUnsupportedExtension)
304		return errors.New("tls: server sent a cookie in a normal ServerHello")
305	}
306
307	if hs.serverHello.selectedGroup != 0 {
308		c.sendAlert(alertDecodeError)
309		return errors.New("tls: malformed key_share extension")
310	}
311
312	if hs.serverHello.serverShare.group == 0 {
313		c.sendAlert(alertIllegalParameter)
314		return errors.New("tls: server did not send a key share")
315	}
316	if hs.serverHello.serverShare.group != hs.ecdheParams.CurveID() {
317		c.sendAlert(alertIllegalParameter)
318		return errors.New("tls: server selected unsupported group")
319	}
320
321	if !hs.serverHello.selectedIdentityPresent {
322		return nil
323	}
324
325	if int(hs.serverHello.selectedIdentity) >= len(hs.hello.pskIdentities) {
326		c.sendAlert(alertIllegalParameter)
327		return errors.New("tls: server selected an invalid PSK")
328	}
329
330	if len(hs.hello.pskIdentities) != 1 || hs.session == nil {
331		return c.sendAlert(alertInternalError)
332	}
333	pskSuite := cipherSuiteTLS13ByID(hs.session.cipherSuite)
334	if pskSuite == nil {
335		return c.sendAlert(alertInternalError)
336	}
337	if pskSuite.hash != hs.suite.hash {
338		c.sendAlert(alertIllegalParameter)
339		return errors.New("tls: server selected an invalid PSK and cipher suite pair")
340	}
341
342	hs.usingPSK = true
343	c.didResume = true
344	c.peerCertificates = hs.session.serverCertificates
345	c.verifiedChains = hs.session.verifiedChains
346	c.ocspResponse = hs.session.ocspResponse
347	c.scts = hs.session.scts
348	return nil
349}
350
351func (hs *clientHandshakeStateTLS13) establishHandshakeKeys() error {
352	c := hs.c
353
354	sharedKey := hs.ecdheParams.SharedKey(hs.serverHello.serverShare.data)
355	if sharedKey == nil {
356		c.sendAlert(alertIllegalParameter)
357		return errors.New("tls: invalid server key share")
358	}
359
360	earlySecret := hs.earlySecret
361	if !hs.usingPSK {
362		earlySecret = hs.suite.extract(nil, nil)
363	}
364	handshakeSecret := hs.suite.extract(sharedKey,
365		hs.suite.deriveSecret(earlySecret, "derived", nil))
366
367	clientSecret := hs.suite.deriveSecret(handshakeSecret,
368		clientHandshakeTrafficLabel, hs.transcript)
369	c.out.exportKey(EncryptionHandshake, hs.suite, clientSecret)
370	c.out.setTrafficSecret(hs.suite, clientSecret)
371	serverSecret := hs.suite.deriveSecret(handshakeSecret,
372		serverHandshakeTrafficLabel, hs.transcript)
373	c.in.exportKey(EncryptionHandshake, hs.suite, serverSecret)
374	c.in.setTrafficSecret(hs.suite, serverSecret)
375
376	err := c.config.writeKeyLog(keyLogLabelClientHandshake, hs.hello.random, clientSecret)
377	if err != nil {
378		c.sendAlert(alertInternalError)
379		return err
380	}
381	err = c.config.writeKeyLog(keyLogLabelServerHandshake, hs.hello.random, serverSecret)
382	if err != nil {
383		c.sendAlert(alertInternalError)
384		return err
385	}
386
387	hs.masterSecret = hs.suite.extract(nil,
388		hs.suite.deriveSecret(handshakeSecret, "derived", nil))
389
390	return nil
391}
392
393func (hs *clientHandshakeStateTLS13) readServerParameters() error {
394	c := hs.c
395
396	msg, err := c.readHandshake()
397	if err != nil {
398		return err
399	}
400
401	encryptedExtensions, ok := msg.(*encryptedExtensionsMsg)
402	if !ok {
403		c.sendAlert(alertUnexpectedMessage)
404		return unexpectedMessageError(encryptedExtensions, msg)
405	}
406	// Notify the caller if 0-RTT was rejected.
407	if !encryptedExtensions.earlyData && hs.hello.earlyData && c.extraConfig != nil && c.extraConfig.Rejected0RTT != nil {
408		c.extraConfig.Rejected0RTT()
409	}
410	c.used0RTT = encryptedExtensions.earlyData
411	if hs.c.extraConfig != nil && hs.c.extraConfig.ReceivedExtensions != nil {
412		hs.c.extraConfig.ReceivedExtensions(typeEncryptedExtensions, encryptedExtensions.additionalExtensions)
413	}
414	hs.transcript.Write(encryptedExtensions.marshal())
415
416	if c.extraConfig != nil && c.extraConfig.EnforceNextProtoSelection {
417		if len(encryptedExtensions.alpnProtocol) == 0 {
418			// the server didn't select an ALPN
419			c.sendAlert(alertNoApplicationProtocol)
420			return errors.New("ALPN negotiation failed. Server didn't offer any protocols")
421		}
422		if mutualProtocol([]string{encryptedExtensions.alpnProtocol}, hs.c.config.NextProtos) == "" {
423			// the protocol selected by the server was not offered
424			c.sendAlert(alertNoApplicationProtocol)
425			return fmt.Errorf("ALPN negotiation failed. Server offered: %q", encryptedExtensions.alpnProtocol)
426		}
427	}
428	if encryptedExtensions.alpnProtocol != "" {
429		if len(hs.hello.alpnProtocols) == 0 {
430			c.sendAlert(alertUnsupportedExtension)
431			return errors.New("tls: server advertised unrequested ALPN extension")
432		}
433		if mutualProtocol([]string{encryptedExtensions.alpnProtocol}, hs.hello.alpnProtocols) == "" {
434			c.sendAlert(alertUnsupportedExtension)
435			return errors.New("tls: server selected unadvertised ALPN protocol")
436		}
437		c.clientProtocol = encryptedExtensions.alpnProtocol
438	}
439	return nil
440}
441
442func (hs *clientHandshakeStateTLS13) readServerCertificate() error {
443	c := hs.c
444
445	// Either a PSK or a certificate is always used, but not both.
446	// See RFC 8446, Section 4.1.1.
447	if hs.usingPSK {
448		// Make sure the connection is still being verified whether or not this
449		// is a resumption. Resumptions currently don't reverify certificates so
450		// they don't call verifyServerCertificate. See Issue 31641.
451		if c.config.VerifyConnection != nil {
452			if err := c.config.VerifyConnection(c.connectionStateLocked()); err != nil {
453				c.sendAlert(alertBadCertificate)
454				return err
455			}
456		}
457		return nil
458	}
459
460	msg, err := c.readHandshake()
461	if err != nil {
462		return err
463	}
464
465	certReq, ok := msg.(*certificateRequestMsgTLS13)
466	if ok {
467		hs.transcript.Write(certReq.marshal())
468
469		hs.certReq = certReq
470
471		msg, err = c.readHandshake()
472		if err != nil {
473			return err
474		}
475	}
476
477	certMsg, ok := msg.(*certificateMsgTLS13)
478	if !ok {
479		c.sendAlert(alertUnexpectedMessage)
480		return unexpectedMessageError(certMsg, msg)
481	}
482	if len(certMsg.certificate.Certificate) == 0 {
483		c.sendAlert(alertDecodeError)
484		return errors.New("tls: received empty certificates message")
485	}
486	hs.transcript.Write(certMsg.marshal())
487
488	c.scts = certMsg.certificate.SignedCertificateTimestamps
489	c.ocspResponse = certMsg.certificate.OCSPStaple
490
491	if err := c.verifyServerCertificate(certMsg.certificate.Certificate); err != nil {
492		return err
493	}
494
495	msg, err = c.readHandshake()
496	if err != nil {
497		return err
498	}
499
500	certVerify, ok := msg.(*certificateVerifyMsg)
501	if !ok {
502		c.sendAlert(alertUnexpectedMessage)
503		return unexpectedMessageError(certVerify, msg)
504	}
505
506	// See RFC 8446, Section 4.4.3.
507	if !isSupportedSignatureAlgorithm(certVerify.signatureAlgorithm, supportedSignatureAlgorithms) {
508		c.sendAlert(alertIllegalParameter)
509		return errors.New("tls: certificate used with invalid signature algorithm")
510	}
511	sigType, sigHash, err := typeAndHashFromSignatureScheme(certVerify.signatureAlgorithm)
512	if err != nil {
513		return c.sendAlert(alertInternalError)
514	}
515	if sigType == signaturePKCS1v15 || sigHash == crypto.SHA1 {
516		c.sendAlert(alertIllegalParameter)
517		return errors.New("tls: certificate used with invalid signature algorithm")
518	}
519	signed := signedMessage(sigHash, serverSignatureContext, hs.transcript)
520	if err := verifyHandshakeSignature(sigType, c.peerCertificates[0].PublicKey,
521		sigHash, signed, certVerify.signature); err != nil {
522		c.sendAlert(alertDecryptError)
523		return errors.New("tls: invalid signature by the server certificate: " + err.Error())
524	}
525
526	hs.transcript.Write(certVerify.marshal())
527
528	return nil
529}
530
531func (hs *clientHandshakeStateTLS13) readServerFinished() error {
532	c := hs.c
533
534	msg, err := c.readHandshake()
535	if err != nil {
536		return err
537	}
538
539	finished, ok := msg.(*finishedMsg)
540	if !ok {
541		c.sendAlert(alertUnexpectedMessage)
542		return unexpectedMessageError(finished, msg)
543	}
544
545	expectedMAC := hs.suite.finishedHash(c.in.trafficSecret, hs.transcript)
546	if !hmac.Equal(expectedMAC, finished.verifyData) {
547		c.sendAlert(alertDecryptError)
548		return errors.New("tls: invalid server finished hash")
549	}
550
551	hs.transcript.Write(finished.marshal())
552
553	// Derive secrets that take context through the server Finished.
554
555	hs.trafficSecret = hs.suite.deriveSecret(hs.masterSecret,
556		clientApplicationTrafficLabel, hs.transcript)
557	serverSecret := hs.suite.deriveSecret(hs.masterSecret,
558		serverApplicationTrafficLabel, hs.transcript)
559	c.in.exportKey(EncryptionApplication, hs.suite, serverSecret)
560	c.in.setTrafficSecret(hs.suite, serverSecret)
561
562	err = c.config.writeKeyLog(keyLogLabelClientTraffic, hs.hello.random, hs.trafficSecret)
563	if err != nil {
564		c.sendAlert(alertInternalError)
565		return err
566	}
567	err = c.config.writeKeyLog(keyLogLabelServerTraffic, hs.hello.random, serverSecret)
568	if err != nil {
569		c.sendAlert(alertInternalError)
570		return err
571	}
572
573	c.ekm = hs.suite.exportKeyingMaterial(hs.masterSecret, hs.transcript)
574
575	return nil
576}
577
578func (hs *clientHandshakeStateTLS13) sendClientCertificate() error {
579	c := hs.c
580
581	if hs.certReq == nil {
582		return nil
583	}
584
585	cert, err := c.getClientCertificate(toCertificateRequestInfo(&certificateRequestInfo{
586		AcceptableCAs:    hs.certReq.certificateAuthorities,
587		SignatureSchemes: hs.certReq.supportedSignatureAlgorithms,
588		Version:          c.vers,
589	}))
590	if err != nil {
591		return err
592	}
593
594	certMsg := new(certificateMsgTLS13)
595
596	certMsg.certificate = *cert
597	certMsg.scts = hs.certReq.scts && len(cert.SignedCertificateTimestamps) > 0
598	certMsg.ocspStapling = hs.certReq.ocspStapling && len(cert.OCSPStaple) > 0
599
600	hs.transcript.Write(certMsg.marshal())
601	if _, err := c.writeRecord(recordTypeHandshake, certMsg.marshal()); err != nil {
602		return err
603	}
604
605	// If we sent an empty certificate message, skip the CertificateVerify.
606	if len(cert.Certificate) == 0 {
607		return nil
608	}
609
610	certVerifyMsg := new(certificateVerifyMsg)
611	certVerifyMsg.hasSignatureAlgorithm = true
612
613	certVerifyMsg.signatureAlgorithm, err = selectSignatureScheme(c.vers, cert, hs.certReq.supportedSignatureAlgorithms)
614	if err != nil {
615		// getClientCertificate returned a certificate incompatible with the
616		// CertificateRequestInfo supported signature algorithms.
617		c.sendAlert(alertHandshakeFailure)
618		return err
619	}
620
621	sigType, sigHash, err := typeAndHashFromSignatureScheme(certVerifyMsg.signatureAlgorithm)
622	if err != nil {
623		return c.sendAlert(alertInternalError)
624	}
625
626	signed := signedMessage(sigHash, clientSignatureContext, hs.transcript)
627	signOpts := crypto.SignerOpts(sigHash)
628	if sigType == signatureRSAPSS {
629		signOpts = &rsa.PSSOptions{SaltLength: rsa.PSSSaltLengthEqualsHash, Hash: sigHash}
630	}
631	sig, err := cert.PrivateKey.(crypto.Signer).Sign(c.config.rand(), signed, signOpts)
632	if err != nil {
633		c.sendAlert(alertInternalError)
634		return errors.New("tls: failed to sign handshake: " + err.Error())
635	}
636	certVerifyMsg.signature = sig
637
638	hs.transcript.Write(certVerifyMsg.marshal())
639	if _, err := c.writeRecord(recordTypeHandshake, certVerifyMsg.marshal()); err != nil {
640		return err
641	}
642
643	return nil
644}
645
646func (hs *clientHandshakeStateTLS13) sendClientFinished() error {
647	c := hs.c
648
649	finished := &finishedMsg{
650		verifyData: hs.suite.finishedHash(c.out.trafficSecret, hs.transcript),
651	}
652
653	hs.transcript.Write(finished.marshal())
654	if _, err := c.writeRecord(recordTypeHandshake, finished.marshal()); err != nil {
655		return err
656	}
657
658	c.out.exportKey(EncryptionApplication, hs.suite, hs.trafficSecret)
659	c.out.setTrafficSecret(hs.suite, hs.trafficSecret)
660
661	if !c.config.SessionTicketsDisabled && c.config.ClientSessionCache != nil {
662		c.resumptionSecret = hs.suite.deriveSecret(hs.masterSecret,
663			resumptionLabel, hs.transcript)
664	}
665
666	return nil
667}
668
669func (c *Conn) handleNewSessionTicket(msg *newSessionTicketMsgTLS13) error {
670	if !c.isClient {
671		c.sendAlert(alertUnexpectedMessage)
672		return errors.New("tls: received new session ticket from a client")
673	}
674
675	if c.config.SessionTicketsDisabled || c.config.ClientSessionCache == nil {
676		return nil
677	}
678
679	// See RFC 8446, Section 4.6.1.
680	if msg.lifetime == 0 {
681		return nil
682	}
683	lifetime := time.Duration(msg.lifetime) * time.Second
684	if lifetime > maxSessionTicketLifetime {
685		c.sendAlert(alertIllegalParameter)
686		return errors.New("tls: received a session ticket with invalid lifetime")
687	}
688
689	cipherSuite := cipherSuiteTLS13ByID(c.cipherSuite)
690	if cipherSuite == nil || c.resumptionSecret == nil {
691		return c.sendAlert(alertInternalError)
692	}
693
694	// We need to save the max_early_data_size that the server sent us, in order
695	// to decide if we're going to try 0-RTT with this ticket.
696	// However, at the same time, the qtls.ClientSessionTicket needs to be equal to
697	// the tls.ClientSessionTicket, so we can't just add a new field to the struct.
698	// We therefore abuse the nonce field (which is a byte slice)
699	nonceWithEarlyData := make([]byte, len(msg.nonce)+4)
700	binary.BigEndian.PutUint32(nonceWithEarlyData, msg.maxEarlyData)
701	copy(nonceWithEarlyData[4:], msg.nonce)
702
703	var appData []byte
704	if c.extraConfig != nil && c.extraConfig.GetAppDataForSessionState != nil {
705		appData = c.extraConfig.GetAppDataForSessionState()
706	}
707	var b cryptobyte.Builder
708	b.AddUint16(clientSessionStateVersion) // revision
709	b.AddUint32(msg.maxEarlyData)
710	b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) {
711		b.AddBytes(appData)
712	})
713	b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) {
714		b.AddBytes(msg.nonce)
715	})
716
717	// Save the resumption_master_secret and nonce instead of deriving the PSK
718	// to do the least amount of work on NewSessionTicket messages before we
719	// know if the ticket will be used. Forward secrecy of resumed connections
720	// is guaranteed by the requirement for pskModeDHE.
721	session := &clientSessionState{
722		sessionTicket:      msg.label,
723		vers:               c.vers,
724		cipherSuite:        c.cipherSuite,
725		masterSecret:       c.resumptionSecret,
726		serverCertificates: c.peerCertificates,
727		verifiedChains:     c.verifiedChains,
728		receivedAt:         c.config.time(),
729		nonce:              b.BytesOrPanic(),
730		useBy:              c.config.time().Add(lifetime),
731		ageAdd:             msg.ageAdd,
732		ocspResponse:       c.ocspResponse,
733		scts:               c.scts,
734	}
735
736	cacheKey := clientSessionCacheKey(c.conn.RemoteAddr(), c.config)
737	c.config.ClientSessionCache.Put(cacheKey, toClientSessionState(session))
738
739	return nil
740}
741