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