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