]> Cypherpunks.ru repositories - gostls13.git/blob - src/crypto/tls/handshake_client_tls13.go
crypto/tls: support QUIC as a transport
[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.c.quic != nil {
176                 return nil
177         }
178         if hs.sentDummyCCS {
179                 return nil
180         }
181         hs.sentDummyCCS = true
182
183         return hs.c.writeChangeCipherRecord()
184 }
185
186 // processHelloRetryRequest handles the HRR in hs.serverHello, modifies and
187 // resends hs.hello, and reads the new ServerHello into hs.serverHello.
188 func (hs *clientHandshakeStateTLS13) processHelloRetryRequest() error {
189         c := hs.c
190
191         // The first ClientHello gets double-hashed into the transcript upon a
192         // HelloRetryRequest. (The idea is that the server might offload transcript
193         // storage to the client in the cookie.) See RFC 8446, Section 4.4.1.
194         chHash := hs.transcript.Sum(nil)
195         hs.transcript.Reset()
196         hs.transcript.Write([]byte{typeMessageHash, 0, 0, uint8(len(chHash))})
197         hs.transcript.Write(chHash)
198         if err := transcriptMsg(hs.serverHello, hs.transcript); err != nil {
199                 return err
200         }
201
202         // The only HelloRetryRequest extensions we support are key_share and
203         // cookie, and clients must abort the handshake if the HRR would not result
204         // in any change in the ClientHello.
205         if hs.serverHello.selectedGroup == 0 && hs.serverHello.cookie == nil {
206                 c.sendAlert(alertIllegalParameter)
207                 return errors.New("tls: server sent an unnecessary HelloRetryRequest message")
208         }
209
210         if hs.serverHello.cookie != nil {
211                 hs.hello.cookie = hs.serverHello.cookie
212         }
213
214         if hs.serverHello.serverShare.group != 0 {
215                 c.sendAlert(alertDecodeError)
216                 return errors.New("tls: received malformed key_share extension")
217         }
218
219         // If the server sent a key_share extension selecting a group, ensure it's
220         // a group we advertised but did not send a key share for, and send a key
221         // share for it this time.
222         if curveID := hs.serverHello.selectedGroup; curveID != 0 {
223                 curveOK := false
224                 for _, id := range hs.hello.supportedCurves {
225                         if id == curveID {
226                                 curveOK = true
227                                 break
228                         }
229                 }
230                 if !curveOK {
231                         c.sendAlert(alertIllegalParameter)
232                         return errors.New("tls: server selected unsupported group")
233                 }
234                 if sentID, _ := curveIDForCurve(hs.ecdheKey.Curve()); sentID == curveID {
235                         c.sendAlert(alertIllegalParameter)
236                         return errors.New("tls: server sent an unnecessary HelloRetryRequest key_share")
237                 }
238                 if _, ok := curveForCurveID(curveID); !ok {
239                         c.sendAlert(alertInternalError)
240                         return errors.New("tls: CurvePreferences includes unsupported curve")
241                 }
242                 key, err := generateECDHEKey(c.config.rand(), curveID)
243                 if err != nil {
244                         c.sendAlert(alertInternalError)
245                         return err
246                 }
247                 hs.ecdheKey = key
248                 hs.hello.keyShares = []keyShare{{group: curveID, data: key.PublicKey().Bytes()}}
249         }
250
251         hs.hello.raw = nil
252         if len(hs.hello.pskIdentities) > 0 {
253                 pskSuite := cipherSuiteTLS13ByID(hs.session.cipherSuite)
254                 if pskSuite == nil {
255                         return c.sendAlert(alertInternalError)
256                 }
257                 if pskSuite.hash == hs.suite.hash {
258                         // Update binders and obfuscated_ticket_age.
259                         ticketAge := uint32(c.config.time().Sub(hs.session.receivedAt) / time.Millisecond)
260                         hs.hello.pskIdentities[0].obfuscatedTicketAge = ticketAge + hs.session.ageAdd
261
262                         transcript := hs.suite.hash.New()
263                         transcript.Write([]byte{typeMessageHash, 0, 0, uint8(len(chHash))})
264                         transcript.Write(chHash)
265                         if err := transcriptMsg(hs.serverHello, transcript); err != nil {
266                                 return err
267                         }
268                         helloBytes, err := hs.hello.marshalWithoutBinders()
269                         if err != nil {
270                                 return err
271                         }
272                         transcript.Write(helloBytes)
273                         pskBinders := [][]byte{hs.suite.finishedHash(hs.binderKey, transcript)}
274                         if err := hs.hello.updateBinders(pskBinders); err != nil {
275                                 return err
276                         }
277                 } else {
278                         // Server selected a cipher suite incompatible with the PSK.
279                         hs.hello.pskIdentities = nil
280                         hs.hello.pskBinders = nil
281                 }
282         }
283
284         if _, err := hs.c.writeHandshakeRecord(hs.hello, hs.transcript); err != nil {
285                 return err
286         }
287
288         // serverHelloMsg is not included in the transcript
289         msg, err := c.readHandshake(nil)
290         if err != nil {
291                 return err
292         }
293
294         serverHello, ok := msg.(*serverHelloMsg)
295         if !ok {
296                 c.sendAlert(alertUnexpectedMessage)
297                 return unexpectedMessageError(serverHello, msg)
298         }
299         hs.serverHello = serverHello
300
301         if err := hs.checkServerHelloOrHRR(); err != nil {
302                 return err
303         }
304
305         return nil
306 }
307
308 func (hs *clientHandshakeStateTLS13) processServerHello() error {
309         c := hs.c
310
311         if bytes.Equal(hs.serverHello.random, helloRetryRequestRandom) {
312                 c.sendAlert(alertUnexpectedMessage)
313                 return errors.New("tls: server sent two HelloRetryRequest messages")
314         }
315
316         if len(hs.serverHello.cookie) != 0 {
317                 c.sendAlert(alertUnsupportedExtension)
318                 return errors.New("tls: server sent a cookie in a normal ServerHello")
319         }
320
321         if hs.serverHello.selectedGroup != 0 {
322                 c.sendAlert(alertDecodeError)
323                 return errors.New("tls: malformed key_share extension")
324         }
325
326         if hs.serverHello.serverShare.group == 0 {
327                 c.sendAlert(alertIllegalParameter)
328                 return errors.New("tls: server did not send a key share")
329         }
330         if sentID, _ := curveIDForCurve(hs.ecdheKey.Curve()); hs.serverHello.serverShare.group != sentID {
331                 c.sendAlert(alertIllegalParameter)
332                 return errors.New("tls: server selected unsupported group")
333         }
334
335         if !hs.serverHello.selectedIdentityPresent {
336                 return nil
337         }
338
339         if int(hs.serverHello.selectedIdentity) >= len(hs.hello.pskIdentities) {
340                 c.sendAlert(alertIllegalParameter)
341                 return errors.New("tls: server selected an invalid PSK")
342         }
343
344         if len(hs.hello.pskIdentities) != 1 || hs.session == nil {
345                 return c.sendAlert(alertInternalError)
346         }
347         pskSuite := cipherSuiteTLS13ByID(hs.session.cipherSuite)
348         if pskSuite == nil {
349                 return c.sendAlert(alertInternalError)
350         }
351         if pskSuite.hash != hs.suite.hash {
352                 c.sendAlert(alertIllegalParameter)
353                 return errors.New("tls: server selected an invalid PSK and cipher suite pair")
354         }
355
356         hs.usingPSK = true
357         c.didResume = true
358         c.peerCertificates = hs.session.serverCertificates
359         c.verifiedChains = hs.session.verifiedChains
360         c.ocspResponse = hs.session.ocspResponse
361         c.scts = hs.session.scts
362         return nil
363 }
364
365 func (hs *clientHandshakeStateTLS13) establishHandshakeKeys() error {
366         c := hs.c
367
368         peerKey, err := hs.ecdheKey.Curve().NewPublicKey(hs.serverHello.serverShare.data)
369         if err != nil {
370                 c.sendAlert(alertIllegalParameter)
371                 return errors.New("tls: invalid server key share")
372         }
373         sharedKey, err := hs.ecdheKey.ECDH(peerKey)
374         if err != nil {
375                 c.sendAlert(alertIllegalParameter)
376                 return errors.New("tls: invalid server key share")
377         }
378
379         earlySecret := hs.earlySecret
380         if !hs.usingPSK {
381                 earlySecret = hs.suite.extract(nil, nil)
382         }
383
384         handshakeSecret := hs.suite.extract(sharedKey,
385                 hs.suite.deriveSecret(earlySecret, "derived", nil))
386
387         clientSecret := hs.suite.deriveSecret(handshakeSecret,
388                 clientHandshakeTrafficLabel, hs.transcript)
389         c.out.setTrafficSecret(hs.suite, QUICEncryptionLevelHandshake, clientSecret)
390         serverSecret := hs.suite.deriveSecret(handshakeSecret,
391                 serverHandshakeTrafficLabel, hs.transcript)
392         c.in.setTrafficSecret(hs.suite, QUICEncryptionLevelHandshake, serverSecret)
393
394         if c.quic != nil {
395                 if c.hand.Len() != 0 {
396                         c.sendAlert(alertUnexpectedMessage)
397                 }
398                 c.quicSetWriteSecret(QUICEncryptionLevelHandshake, hs.suite.id, clientSecret)
399                 c.quicSetReadSecret(QUICEncryptionLevelHandshake, hs.suite.id, serverSecret)
400         }
401
402         err = c.config.writeKeyLog(keyLogLabelClientHandshake, hs.hello.random, clientSecret)
403         if err != nil {
404                 c.sendAlert(alertInternalError)
405                 return err
406         }
407         err = c.config.writeKeyLog(keyLogLabelServerHandshake, hs.hello.random, serverSecret)
408         if err != nil {
409                 c.sendAlert(alertInternalError)
410                 return err
411         }
412
413         hs.masterSecret = hs.suite.extract(nil,
414                 hs.suite.deriveSecret(handshakeSecret, "derived", nil))
415
416         return nil
417 }
418
419 func (hs *clientHandshakeStateTLS13) readServerParameters() error {
420         c := hs.c
421
422         msg, err := c.readHandshake(hs.transcript)
423         if err != nil {
424                 return err
425         }
426
427         encryptedExtensions, ok := msg.(*encryptedExtensionsMsg)
428         if !ok {
429                 c.sendAlert(alertUnexpectedMessage)
430                 return unexpectedMessageError(encryptedExtensions, msg)
431         }
432
433         if err := checkALPN(hs.hello.alpnProtocols, encryptedExtensions.alpnProtocol, c.quic != nil); err != nil {
434                 // RFC 8446 specifies that no_application_protocol is sent by servers, but
435                 // does not specify how clients handle the selection of an incompatible protocol.
436                 // RFC 9001 Section 8.1 specifies that QUIC clients send no_application_protocol
437                 // in this case. Always sending no_application_protocol seems reasonable.
438                 c.sendAlert(alertNoApplicationProtocol)
439                 return err
440         }
441         c.clientProtocol = encryptedExtensions.alpnProtocol
442
443         if c.quic != nil {
444                 if encryptedExtensions.quicTransportParameters == nil {
445                         // RFC 9001 Section 8.2.
446                         c.sendAlert(alertMissingExtension)
447                         return errors.New("tls: server did not send a quic_transport_parameters extension")
448                 }
449                 c.quicSetTransportParameters(encryptedExtensions.quicTransportParameters)
450         } else {
451                 if encryptedExtensions.quicTransportParameters != nil {
452                         c.sendAlert(alertUnsupportedExtension)
453                         return errors.New("tls: server sent an unexpected quic_transport_parameters extension")
454                 }
455         }
456
457         return nil
458 }
459
460 func (hs *clientHandshakeStateTLS13) readServerCertificate() error {
461         c := hs.c
462
463         // Either a PSK or a certificate is always used, but not both.
464         // See RFC 8446, Section 4.1.1.
465         if hs.usingPSK {
466                 // Make sure the connection is still being verified whether or not this
467                 // is a resumption. Resumptions currently don't reverify certificates so
468                 // they don't call verifyServerCertificate. See Issue 31641.
469                 if c.config.VerifyConnection != nil {
470                         if err := c.config.VerifyConnection(c.connectionStateLocked()); err != nil {
471                                 c.sendAlert(alertBadCertificate)
472                                 return err
473                         }
474                 }
475                 return nil
476         }
477
478         msg, err := c.readHandshake(hs.transcript)
479         if err != nil {
480                 return err
481         }
482
483         certReq, ok := msg.(*certificateRequestMsgTLS13)
484         if ok {
485                 hs.certReq = certReq
486
487                 msg, err = c.readHandshake(hs.transcript)
488                 if err != nil {
489                         return err
490                 }
491         }
492
493         certMsg, ok := msg.(*certificateMsgTLS13)
494         if !ok {
495                 c.sendAlert(alertUnexpectedMessage)
496                 return unexpectedMessageError(certMsg, msg)
497         }
498         if len(certMsg.certificate.Certificate) == 0 {
499                 c.sendAlert(alertDecodeError)
500                 return errors.New("tls: received empty certificates message")
501         }
502
503         c.scts = certMsg.certificate.SignedCertificateTimestamps
504         c.ocspResponse = certMsg.certificate.OCSPStaple
505
506         if err := c.verifyServerCertificate(certMsg.certificate.Certificate); err != nil {
507                 return err
508         }
509
510         // certificateVerifyMsg is included in the transcript, but not until
511         // after we verify the handshake signature, since the state before
512         // this message was sent is used.
513         msg, err = c.readHandshake(nil)
514         if err != nil {
515                 return err
516         }
517
518         certVerify, ok := msg.(*certificateVerifyMsg)
519         if !ok {
520                 c.sendAlert(alertUnexpectedMessage)
521                 return unexpectedMessageError(certVerify, msg)
522         }
523
524         // See RFC 8446, Section 4.4.3.
525         if !isSupportedSignatureAlgorithm(certVerify.signatureAlgorithm, supportedSignatureAlgorithms()) {
526                 c.sendAlert(alertIllegalParameter)
527                 return errors.New("tls: certificate used with invalid signature algorithm")
528         }
529         sigType, sigHash, err := typeAndHashFromSignatureScheme(certVerify.signatureAlgorithm)
530         if err != nil {
531                 return c.sendAlert(alertInternalError)
532         }
533         if sigType == signaturePKCS1v15 || sigHash == crypto.SHA1 {
534                 c.sendAlert(alertIllegalParameter)
535                 return errors.New("tls: certificate used with invalid signature algorithm")
536         }
537         signed := signedMessage(sigHash, serverSignatureContext, hs.transcript)
538         if err := verifyHandshakeSignature(sigType, c.peerCertificates[0].PublicKey,
539                 sigHash, signed, certVerify.signature); err != nil {
540                 c.sendAlert(alertDecryptError)
541                 return errors.New("tls: invalid signature by the server certificate: " + err.Error())
542         }
543
544         if err := transcriptMsg(certVerify, hs.transcript); err != nil {
545                 return err
546         }
547
548         return nil
549 }
550
551 func (hs *clientHandshakeStateTLS13) readServerFinished() error {
552         c := hs.c
553
554         // finishedMsg is included in the transcript, but not until after we
555         // check the client version, since the state before this message was
556         // sent is used during verification.
557         msg, err := c.readHandshake(nil)
558         if err != nil {
559                 return err
560         }
561
562         finished, ok := msg.(*finishedMsg)
563         if !ok {
564                 c.sendAlert(alertUnexpectedMessage)
565                 return unexpectedMessageError(finished, msg)
566         }
567
568         expectedMAC := hs.suite.finishedHash(c.in.trafficSecret, hs.transcript)
569         if !hmac.Equal(expectedMAC, finished.verifyData) {
570                 c.sendAlert(alertDecryptError)
571                 return errors.New("tls: invalid server finished hash")
572         }
573
574         if err := transcriptMsg(finished, hs.transcript); err != nil {
575                 return err
576         }
577
578         // Derive secrets that take context through the server Finished.
579
580         hs.trafficSecret = hs.suite.deriveSecret(hs.masterSecret,
581                 clientApplicationTrafficLabel, hs.transcript)
582         serverSecret := hs.suite.deriveSecret(hs.masterSecret,
583                 serverApplicationTrafficLabel, hs.transcript)
584         c.in.setTrafficSecret(hs.suite, QUICEncryptionLevelApplication, serverSecret)
585
586         err = c.config.writeKeyLog(keyLogLabelClientTraffic, hs.hello.random, hs.trafficSecret)
587         if err != nil {
588                 c.sendAlert(alertInternalError)
589                 return err
590         }
591         err = c.config.writeKeyLog(keyLogLabelServerTraffic, hs.hello.random, serverSecret)
592         if err != nil {
593                 c.sendAlert(alertInternalError)
594                 return err
595         }
596
597         c.ekm = hs.suite.exportKeyingMaterial(hs.masterSecret, hs.transcript)
598
599         return nil
600 }
601
602 func (hs *clientHandshakeStateTLS13) sendClientCertificate() error {
603         c := hs.c
604
605         if hs.certReq == nil {
606                 return nil
607         }
608
609         cert, err := c.getClientCertificate(&CertificateRequestInfo{
610                 AcceptableCAs:    hs.certReq.certificateAuthorities,
611                 SignatureSchemes: hs.certReq.supportedSignatureAlgorithms,
612                 Version:          c.vers,
613                 ctx:              hs.ctx,
614         })
615         if err != nil {
616                 return err
617         }
618
619         certMsg := new(certificateMsgTLS13)
620
621         certMsg.certificate = *cert
622         certMsg.scts = hs.certReq.scts && len(cert.SignedCertificateTimestamps) > 0
623         certMsg.ocspStapling = hs.certReq.ocspStapling && len(cert.OCSPStaple) > 0
624
625         if _, err := hs.c.writeHandshakeRecord(certMsg, hs.transcript); err != nil {
626                 return err
627         }
628
629         // If we sent an empty certificate message, skip the CertificateVerify.
630         if len(cert.Certificate) == 0 {
631                 return nil
632         }
633
634         certVerifyMsg := new(certificateVerifyMsg)
635         certVerifyMsg.hasSignatureAlgorithm = true
636
637         certVerifyMsg.signatureAlgorithm, err = selectSignatureScheme(c.vers, cert, hs.certReq.supportedSignatureAlgorithms)
638         if err != nil {
639                 // getClientCertificate returned a certificate incompatible with the
640                 // CertificateRequestInfo supported signature algorithms.
641                 c.sendAlert(alertHandshakeFailure)
642                 return err
643         }
644
645         sigType, sigHash, err := typeAndHashFromSignatureScheme(certVerifyMsg.signatureAlgorithm)
646         if err != nil {
647                 return c.sendAlert(alertInternalError)
648         }
649
650         signed := signedMessage(sigHash, clientSignatureContext, hs.transcript)
651         signOpts := crypto.SignerOpts(sigHash)
652         if sigType == signatureRSAPSS {
653                 signOpts = &rsa.PSSOptions{SaltLength: rsa.PSSSaltLengthEqualsHash, Hash: sigHash}
654         }
655         sig, err := cert.PrivateKey.(crypto.Signer).Sign(c.config.rand(), signed, signOpts)
656         if err != nil {
657                 c.sendAlert(alertInternalError)
658                 return errors.New("tls: failed to sign handshake: " + err.Error())
659         }
660         certVerifyMsg.signature = sig
661
662         if _, err := hs.c.writeHandshakeRecord(certVerifyMsg, hs.transcript); err != nil {
663                 return err
664         }
665
666         return nil
667 }
668
669 func (hs *clientHandshakeStateTLS13) sendClientFinished() error {
670         c := hs.c
671
672         finished := &finishedMsg{
673                 verifyData: hs.suite.finishedHash(c.out.trafficSecret, hs.transcript),
674         }
675
676         if _, err := hs.c.writeHandshakeRecord(finished, hs.transcript); err != nil {
677                 return err
678         }
679
680         c.out.setTrafficSecret(hs.suite, QUICEncryptionLevelApplication, hs.trafficSecret)
681
682         if !c.config.SessionTicketsDisabled && c.config.ClientSessionCache != nil {
683                 c.resumptionSecret = hs.suite.deriveSecret(hs.masterSecret,
684                         resumptionLabel, hs.transcript)
685         }
686
687         if c.quic != nil {
688                 if c.hand.Len() != 0 {
689                         c.sendAlert(alertUnexpectedMessage)
690                 }
691                 c.quicSetWriteSecret(QUICEncryptionLevelApplication, hs.suite.id, hs.trafficSecret)
692         }
693
694         return nil
695 }
696
697 func (c *Conn) handleNewSessionTicket(msg *newSessionTicketMsgTLS13) error {
698         if !c.isClient {
699                 c.sendAlert(alertUnexpectedMessage)
700                 return errors.New("tls: received new session ticket from a client")
701         }
702
703         if c.config.SessionTicketsDisabled || c.config.ClientSessionCache == nil {
704                 return nil
705         }
706
707         // See RFC 8446, Section 4.6.1.
708         if msg.lifetime == 0 {
709                 return nil
710         }
711         lifetime := time.Duration(msg.lifetime) * time.Second
712         if lifetime > maxSessionTicketLifetime {
713                 c.sendAlert(alertIllegalParameter)
714                 return errors.New("tls: received a session ticket with invalid lifetime")
715         }
716
717         cipherSuite := cipherSuiteTLS13ByID(c.cipherSuite)
718         if cipherSuite == nil || c.resumptionSecret == nil {
719                 return c.sendAlert(alertInternalError)
720         }
721
722         // Save the resumption_master_secret and nonce instead of deriving the PSK
723         // to do the least amount of work on NewSessionTicket messages before we
724         // know if the ticket will be used. Forward secrecy of resumed connections
725         // is guaranteed by the requirement for pskModeDHE.
726         session := &ClientSessionState{
727                 sessionTicket:      msg.label,
728                 vers:               c.vers,
729                 cipherSuite:        c.cipherSuite,
730                 masterSecret:       c.resumptionSecret,
731                 serverCertificates: c.peerCertificates,
732                 verifiedChains:     c.verifiedChains,
733                 receivedAt:         c.config.time(),
734                 nonce:              msg.nonce,
735                 useBy:              c.config.time().Add(lifetime),
736                 ageAdd:             msg.ageAdd,
737                 ocspResponse:       c.ocspResponse,
738                 scts:               c.scts,
739         }
740
741         cacheKey := c.clientSessionCacheKey()
742         if cacheKey != "" {
743                 c.config.ClientSessionCache.Put(cacheKey, session)
744         }
745
746         return nil
747 }