]> Cypherpunks.ru repositories - gostls13.git/blob - src/crypto/tls/handshake_client_tls13.go
[dev.boringcrypto] all: merge master (2f0da6d) into dev.boringcrypto
[gostls13.git] / src / crypto / tls / handshake_client_tls13.go
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
5 package tls
6
7 import (
8         "bytes"
9         "crypto"
10         "crypto/hmac"
11         "crypto/rsa"
12         "errors"
13         "hash"
14         "sync/atomic"
15         "time"
16 )
17
18 type clientHandshakeStateTLS13 struct {
19         c           *Conn
20         serverHello *serverHelloMsg
21         hello       *clientHelloMsg
22         ecdheParams ecdheParameters
23
24         session     *ClientSessionState
25         earlySecret []byte
26         binderKey   []byte
27
28         certReq       *certificateRequestMsgTLS13
29         usingPSK      bool
30         sentDummyCCS  bool
31         suite         *cipherSuiteTLS13
32         transcript    hash.Hash
33         masterSecret  []byte
34         trafficSecret []byte // client_application_traffic_secret_0
35 }
36
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 {
40         c := hs.c
41
42         if needFIPS() {
43                 return errors.New("tls: internal error: TLS 1.3 reached in FIPS mode")
44         }
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.
112 func (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.
167 func (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.
179 func (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         hs.transcript.Write(hs.hello.marshal())
266         if _, err := c.writeRecord(recordTypeHandshake, hs.hello.marshal()); err != nil {
267                 return err
268         }
269
270         msg, err := c.readHandshake()
271         if err != nil {
272                 return err
273         }
274
275         serverHello, ok := msg.(*serverHelloMsg)
276         if !ok {
277                 c.sendAlert(alertUnexpectedMessage)
278                 return unexpectedMessageError(serverHello, msg)
279         }
280         hs.serverHello = serverHello
281
282         if err := hs.checkServerHelloOrHRR(); err != nil {
283                 return err
284         }
285
286         return nil
287 }
288
289 func (hs *clientHandshakeStateTLS13) processServerHello() error {
290         c := hs.c
291
292         if bytes.Equal(hs.serverHello.random, helloRetryRequestRandom) {
293                 c.sendAlert(alertUnexpectedMessage)
294                 return errors.New("tls: server sent two HelloRetryRequest messages")
295         }
296
297         if len(hs.serverHello.cookie) != 0 {
298                 c.sendAlert(alertUnsupportedExtension)
299                 return errors.New("tls: server sent a cookie in a normal ServerHello")
300         }
301
302         if hs.serverHello.selectedGroup != 0 {
303                 c.sendAlert(alertDecodeError)
304                 return errors.New("tls: malformed key_share extension")
305         }
306
307         if hs.serverHello.serverShare.group == 0 {
308                 c.sendAlert(alertIllegalParameter)
309                 return errors.New("tls: server did not send a key share")
310         }
311         if hs.serverHello.serverShare.group != hs.ecdheParams.CurveID() {
312                 c.sendAlert(alertIllegalParameter)
313                 return errors.New("tls: server selected unsupported group")
314         }
315
316         if !hs.serverHello.selectedIdentityPresent {
317                 return nil
318         }
319
320         if int(hs.serverHello.selectedIdentity) >= len(hs.hello.pskIdentities) {
321                 c.sendAlert(alertIllegalParameter)
322                 return errors.New("tls: server selected an invalid PSK")
323         }
324
325         if len(hs.hello.pskIdentities) != 1 || hs.session == nil {
326                 return c.sendAlert(alertInternalError)
327         }
328         pskSuite := cipherSuiteTLS13ByID(hs.session.cipherSuite)
329         if pskSuite == nil {
330                 return c.sendAlert(alertInternalError)
331         }
332         if pskSuite.hash != hs.suite.hash {
333                 c.sendAlert(alertIllegalParameter)
334                 return errors.New("tls: server selected an invalid PSK and cipher suite pair")
335         }
336
337         hs.usingPSK = true
338         c.didResume = true
339         c.peerCertificates = hs.session.serverCertificates
340         c.verifiedChains = hs.session.verifiedChains
341         c.ocspResponse = hs.session.ocspResponse
342         c.scts = hs.session.scts
343         return nil
344 }
345
346 func (hs *clientHandshakeStateTLS13) establishHandshakeKeys() error {
347         c := hs.c
348
349         sharedKey := hs.ecdheParams.SharedKey(hs.serverHello.serverShare.data)
350         if sharedKey == nil {
351                 c.sendAlert(alertIllegalParameter)
352                 return errors.New("tls: invalid server key share")
353         }
354
355         earlySecret := hs.earlySecret
356         if !hs.usingPSK {
357                 earlySecret = hs.suite.extract(nil, nil)
358         }
359         handshakeSecret := hs.suite.extract(sharedKey,
360                 hs.suite.deriveSecret(earlySecret, "derived", nil))
361
362         clientSecret := hs.suite.deriveSecret(handshakeSecret,
363                 clientHandshakeTrafficLabel, hs.transcript)
364         c.out.setTrafficSecret(hs.suite, clientSecret)
365         serverSecret := hs.suite.deriveSecret(handshakeSecret,
366                 serverHandshakeTrafficLabel, hs.transcript)
367         c.in.setTrafficSecret(hs.suite, serverSecret)
368
369         err := c.config.writeKeyLog(keyLogLabelClientHandshake, hs.hello.random, clientSecret)
370         if err != nil {
371                 c.sendAlert(alertInternalError)
372                 return err
373         }
374         err = c.config.writeKeyLog(keyLogLabelServerHandshake, hs.hello.random, serverSecret)
375         if err != nil {
376                 c.sendAlert(alertInternalError)
377                 return err
378         }
379
380         hs.masterSecret = hs.suite.extract(nil,
381                 hs.suite.deriveSecret(handshakeSecret, "derived", nil))
382
383         return nil
384 }
385
386 func (hs *clientHandshakeStateTLS13) readServerParameters() error {
387         c := hs.c
388
389         msg, err := c.readHandshake()
390         if err != nil {
391                 return err
392         }
393
394         encryptedExtensions, ok := msg.(*encryptedExtensionsMsg)
395         if !ok {
396                 c.sendAlert(alertUnexpectedMessage)
397                 return unexpectedMessageError(encryptedExtensions, msg)
398         }
399         hs.transcript.Write(encryptedExtensions.marshal())
400
401         if encryptedExtensions.alpnProtocol != "" {
402                 if len(hs.hello.alpnProtocols) == 0 {
403                         c.sendAlert(alertUnsupportedExtension)
404                         return errors.New("tls: server advertised unrequested ALPN extension")
405                 }
406                 if mutualProtocol([]string{encryptedExtensions.alpnProtocol}, hs.hello.alpnProtocols) == "" {
407                         c.sendAlert(alertUnsupportedExtension)
408                         return errors.New("tls: server selected unadvertised ALPN protocol")
409                 }
410                 c.clientProtocol = encryptedExtensions.alpnProtocol
411         }
412
413         return nil
414 }
415
416 func (hs *clientHandshakeStateTLS13) readServerCertificate() error {
417         c := hs.c
418
419         // Either a PSK or a certificate is always used, but not both.
420         // See RFC 8446, Section 4.1.1.
421         if hs.usingPSK {
422                 // Make sure the connection is still being verified whether or not this
423                 // is a resumption. Resumptions currently don't reverify certificates so
424                 // they don't call verifyServerCertificate. See Issue 31641.
425                 if c.config.VerifyConnection != nil {
426                         if err := c.config.VerifyConnection(c.connectionStateLocked()); err != nil {
427                                 c.sendAlert(alertBadCertificate)
428                                 return err
429                         }
430                 }
431                 return nil
432         }
433
434         msg, err := c.readHandshake()
435         if err != nil {
436                 return err
437         }
438
439         certReq, ok := msg.(*certificateRequestMsgTLS13)
440         if ok {
441                 hs.transcript.Write(certReq.marshal())
442
443                 hs.certReq = certReq
444
445                 msg, err = c.readHandshake()
446                 if err != nil {
447                         return err
448                 }
449         }
450
451         certMsg, ok := msg.(*certificateMsgTLS13)
452         if !ok {
453                 c.sendAlert(alertUnexpectedMessage)
454                 return unexpectedMessageError(certMsg, msg)
455         }
456         if len(certMsg.certificate.Certificate) == 0 {
457                 c.sendAlert(alertDecodeError)
458                 return errors.New("tls: received empty certificates message")
459         }
460         hs.transcript.Write(certMsg.marshal())
461
462         c.scts = certMsg.certificate.SignedCertificateTimestamps
463         c.ocspResponse = certMsg.certificate.OCSPStaple
464
465         if err := c.verifyServerCertificate(certMsg.certificate.Certificate); err != nil {
466                 return err
467         }
468
469         msg, err = c.readHandshake()
470         if err != nil {
471                 return err
472         }
473
474         certVerify, ok := msg.(*certificateVerifyMsg)
475         if !ok {
476                 c.sendAlert(alertUnexpectedMessage)
477                 return unexpectedMessageError(certVerify, msg)
478         }
479
480         // See RFC 8446, Section 4.4.3.
481         if !isSupportedSignatureAlgorithm(certVerify.signatureAlgorithm, supportedSignatureAlgorithms()) {
482                 c.sendAlert(alertIllegalParameter)
483                 return errors.New("tls: certificate used with invalid signature algorithm")
484         }
485         sigType, sigHash, err := typeAndHashFromSignatureScheme(certVerify.signatureAlgorithm)
486         if err != nil {
487                 return c.sendAlert(alertInternalError)
488         }
489         if sigType == signaturePKCS1v15 || sigHash == crypto.SHA1 {
490                 c.sendAlert(alertIllegalParameter)
491                 return errors.New("tls: certificate used with invalid signature algorithm")
492         }
493         signed := signedMessage(sigHash, serverSignatureContext, hs.transcript)
494         if err := verifyHandshakeSignature(sigType, c.peerCertificates[0].PublicKey,
495                 sigHash, signed, certVerify.signature); err != nil {
496                 c.sendAlert(alertDecryptError)
497                 return errors.New("tls: invalid signature by the server certificate: " + err.Error())
498         }
499
500         hs.transcript.Write(certVerify.marshal())
501
502         return nil
503 }
504
505 func (hs *clientHandshakeStateTLS13) readServerFinished() error {
506         c := hs.c
507
508         msg, err := c.readHandshake()
509         if err != nil {
510                 return err
511         }
512
513         finished, ok := msg.(*finishedMsg)
514         if !ok {
515                 c.sendAlert(alertUnexpectedMessage)
516                 return unexpectedMessageError(finished, msg)
517         }
518
519         expectedMAC := hs.suite.finishedHash(c.in.trafficSecret, hs.transcript)
520         if !hmac.Equal(expectedMAC, finished.verifyData) {
521                 c.sendAlert(alertDecryptError)
522                 return errors.New("tls: invalid server finished hash")
523         }
524
525         hs.transcript.Write(finished.marshal())
526
527         // Derive secrets that take context through the server Finished.
528
529         hs.trafficSecret = hs.suite.deriveSecret(hs.masterSecret,
530                 clientApplicationTrafficLabel, hs.transcript)
531         serverSecret := hs.suite.deriveSecret(hs.masterSecret,
532                 serverApplicationTrafficLabel, hs.transcript)
533         c.in.setTrafficSecret(hs.suite, serverSecret)
534
535         err = c.config.writeKeyLog(keyLogLabelClientTraffic, hs.hello.random, hs.trafficSecret)
536         if err != nil {
537                 c.sendAlert(alertInternalError)
538                 return err
539         }
540         err = c.config.writeKeyLog(keyLogLabelServerTraffic, hs.hello.random, serverSecret)
541         if err != nil {
542                 c.sendAlert(alertInternalError)
543                 return err
544         }
545
546         c.ekm = hs.suite.exportKeyingMaterial(hs.masterSecret, hs.transcript)
547
548         return nil
549 }
550
551 func (hs *clientHandshakeStateTLS13) sendClientCertificate() error {
552         c := hs.c
553
554         if hs.certReq == nil {
555                 return nil
556         }
557
558         cert, err := c.getClientCertificate(&CertificateRequestInfo{
559                 AcceptableCAs:    hs.certReq.certificateAuthorities,
560                 SignatureSchemes: hs.certReq.supportedSignatureAlgorithms,
561                 Version:          c.vers,
562         })
563         if err != nil {
564                 return err
565         }
566
567         certMsg := new(certificateMsgTLS13)
568
569         certMsg.certificate = *cert
570         certMsg.scts = hs.certReq.scts && len(cert.SignedCertificateTimestamps) > 0
571         certMsg.ocspStapling = hs.certReq.ocspStapling && len(cert.OCSPStaple) > 0
572
573         hs.transcript.Write(certMsg.marshal())
574         if _, err := c.writeRecord(recordTypeHandshake, certMsg.marshal()); err != nil {
575                 return err
576         }
577
578         // If we sent an empty certificate message, skip the CertificateVerify.
579         if len(cert.Certificate) == 0 {
580                 return nil
581         }
582
583         certVerifyMsg := new(certificateVerifyMsg)
584         certVerifyMsg.hasSignatureAlgorithm = true
585
586         certVerifyMsg.signatureAlgorithm, err = selectSignatureScheme(c.vers, cert, hs.certReq.supportedSignatureAlgorithms)
587         if err != nil {
588                 // getClientCertificate returned a certificate incompatible with the
589                 // CertificateRequestInfo supported signature algorithms.
590                 c.sendAlert(alertHandshakeFailure)
591                 return err
592         }
593
594         sigType, sigHash, err := typeAndHashFromSignatureScheme(certVerifyMsg.signatureAlgorithm)
595         if err != nil {
596                 return c.sendAlert(alertInternalError)
597         }
598
599         signed := signedMessage(sigHash, clientSignatureContext, hs.transcript)
600         signOpts := crypto.SignerOpts(sigHash)
601         if sigType == signatureRSAPSS {
602                 signOpts = &rsa.PSSOptions{SaltLength: rsa.PSSSaltLengthEqualsHash, Hash: sigHash}
603         }
604         sig, err := cert.PrivateKey.(crypto.Signer).Sign(c.config.rand(), signed, signOpts)
605         if err != nil {
606                 c.sendAlert(alertInternalError)
607                 return errors.New("tls: failed to sign handshake: " + err.Error())
608         }
609         certVerifyMsg.signature = sig
610
611         hs.transcript.Write(certVerifyMsg.marshal())
612         if _, err := c.writeRecord(recordTypeHandshake, certVerifyMsg.marshal()); err != nil {
613                 return err
614         }
615
616         return nil
617 }
618
619 func (hs *clientHandshakeStateTLS13) sendClientFinished() error {
620         c := hs.c
621
622         finished := &finishedMsg{
623                 verifyData: hs.suite.finishedHash(c.out.trafficSecret, hs.transcript),
624         }
625
626         hs.transcript.Write(finished.marshal())
627         if _, err := c.writeRecord(recordTypeHandshake, finished.marshal()); err != nil {
628                 return err
629         }
630
631         c.out.setTrafficSecret(hs.suite, hs.trafficSecret)
632
633         if !c.config.SessionTicketsDisabled && c.config.ClientSessionCache != nil {
634                 c.resumptionSecret = hs.suite.deriveSecret(hs.masterSecret,
635                         resumptionLabel, hs.transcript)
636         }
637
638         return nil
639 }
640
641 func (c *Conn) handleNewSessionTicket(msg *newSessionTicketMsgTLS13) error {
642         if !c.isClient {
643                 c.sendAlert(alertUnexpectedMessage)
644                 return errors.New("tls: received new session ticket from a client")
645         }
646
647         if c.config.SessionTicketsDisabled || c.config.ClientSessionCache == nil {
648                 return nil
649         }
650
651         // See RFC 8446, Section 4.6.1.
652         if msg.lifetime == 0 {
653                 return nil
654         }
655         lifetime := time.Duration(msg.lifetime) * time.Second
656         if lifetime > maxSessionTicketLifetime {
657                 c.sendAlert(alertIllegalParameter)
658                 return errors.New("tls: received a session ticket with invalid lifetime")
659         }
660
661         cipherSuite := cipherSuiteTLS13ByID(c.cipherSuite)
662         if cipherSuite == nil || c.resumptionSecret == nil {
663                 return c.sendAlert(alertInternalError)
664         }
665
666         // Save the resumption_master_secret and nonce instead of deriving the PSK
667         // to do the least amount of work on NewSessionTicket messages before we
668         // know if the ticket will be used. Forward secrecy of resumed connections
669         // is guaranteed by the requirement for pskModeDHE.
670         session := &ClientSessionState{
671                 sessionTicket:      msg.label,
672                 vers:               c.vers,
673                 cipherSuite:        c.cipherSuite,
674                 masterSecret:       c.resumptionSecret,
675                 serverCertificates: c.peerCertificates,
676                 verifiedChains:     c.verifiedChains,
677                 receivedAt:         c.config.time(),
678                 nonce:              msg.nonce,
679                 useBy:              c.config.time().Add(lifetime),
680                 ageAdd:             msg.ageAdd,
681                 ocspResponse:       c.ocspResponse,
682                 scts:               c.scts,
683         }
684
685         cacheKey := clientSessionCacheKey(c.conn.RemoteAddr(), c.config)
686         c.config.ClientSessionCache.Put(cacheKey, session)
687
688         return nil
689 }