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