Source file
src/crypto/tls/handshake_client_tls13.go
1
2
3
4
5 package tls
6
7 import (
8 "bytes"
9 "context"
10 "crypto"
11 "crypto/hmac"
12 "crypto/internal/mlkem768"
13 "crypto/rsa"
14 "crypto/subtle"
15 "errors"
16 "hash"
17 "slices"
18 "time"
19 )
20
21 type clientHandshakeStateTLS13 struct {
22 c *Conn
23 ctx context.Context
24 serverHello *serverHelloMsg
25 hello *clientHelloMsg
26 keyShareKeys *keySharePrivateKeys
27
28 session *SessionState
29 earlySecret []byte
30 binderKey []byte
31
32 certReq *certificateRequestMsgTLS13
33 usingPSK bool
34 sentDummyCCS bool
35 suite *cipherSuiteTLS13
36 transcript hash.Hash
37 masterSecret []byte
38 trafficSecret []byte
39
40 echContext *echContext
41 }
42
43
44
45 func (hs *clientHandshakeStateTLS13) handshake() error {
46 c := hs.c
47
48
49
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
56 if hs.keyShareKeys == nil || hs.keyShareKeys.ecdhe == nil || len(hs.hello.keyShares) == 0 {
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 hs.echContext != nil {
71 hs.echContext.innerTranscript = hs.suite.hash.New()
72 if err := transcriptMsg(hs.echContext.innerHello, hs.echContext.innerTranscript); err != nil {
73 return err
74 }
75 }
76
77 if bytes.Equal(hs.serverHello.random, helloRetryRequestRandom) {
78 if err := hs.sendDummyChangeCipherSpec(); err != nil {
79 return err
80 }
81 if err := hs.processHelloRetryRequest(); err != nil {
82 return err
83 }
84 }
85
86 var echRetryConfigList []byte
87 if hs.echContext != nil {
88 confTranscript := cloneHash(hs.echContext.innerTranscript, hs.suite.hash)
89 confTranscript.Write(hs.serverHello.original[:30])
90 confTranscript.Write(make([]byte, 8))
91 confTranscript.Write(hs.serverHello.original[38:])
92 acceptConfirmation := hs.suite.expandLabel(
93 hs.suite.extract(hs.echContext.innerHello.random, nil),
94 "ech accept confirmation",
95 confTranscript.Sum(nil),
96 8,
97 )
98 if subtle.ConstantTimeCompare(acceptConfirmation, hs.serverHello.random[len(hs.serverHello.random)-8:]) == 1 {
99 hs.hello = hs.echContext.innerHello
100 c.serverName = c.config.ServerName
101 hs.transcript = hs.echContext.innerTranscript
102 c.echAccepted = true
103
104 if hs.serverHello.encryptedClientHello != nil {
105 c.sendAlert(alertUnsupportedExtension)
106 return errors.New("tls: unexpected encrypted_client_hello extension in server hello despite ECH being accepted")
107 }
108
109 if hs.hello.serverName == "" && hs.serverHello.serverNameAck {
110 c.sendAlert(alertUnsupportedExtension)
111 return errors.New("tls: unexpected server_name extension in server hello")
112 }
113 } else {
114 hs.echContext.echRejected = true
115
116
117 echRetryConfigList = hs.serverHello.encryptedClientHello
118 }
119 }
120
121 if err := transcriptMsg(hs.serverHello, hs.transcript); err != nil {
122 return err
123 }
124
125 c.buffering = true
126 if err := hs.processServerHello(); err != nil {
127 return err
128 }
129 if err := hs.sendDummyChangeCipherSpec(); err != nil {
130 return err
131 }
132 if err := hs.establishHandshakeKeys(); err != nil {
133 return err
134 }
135 if err := hs.readServerParameters(); err != nil {
136 return err
137 }
138 if err := hs.readServerCertificate(); err != nil {
139 return err
140 }
141 if err := hs.readServerFinished(); err != nil {
142 return err
143 }
144 if err := hs.sendClientCertificate(); err != nil {
145 return err
146 }
147 if err := hs.sendClientFinished(); err != nil {
148 return err
149 }
150 if _, err := c.flush(); err != nil {
151 return err
152 }
153
154 if hs.echContext != nil && hs.echContext.echRejected {
155 c.sendAlert(alertECHRequired)
156 return &ECHRejectionError{echRetryConfigList}
157 }
158
159 c.isHandshakeComplete.Store(true)
160
161 return nil
162 }
163
164
165
166 func (hs *clientHandshakeStateTLS13) checkServerHelloOrHRR() error {
167 c := hs.c
168
169 if hs.serverHello.supportedVersion == 0 {
170 c.sendAlert(alertMissingExtension)
171 return errors.New("tls: server selected TLS 1.3 using the legacy version field")
172 }
173
174 if hs.serverHello.supportedVersion != VersionTLS13 {
175 c.sendAlert(alertIllegalParameter)
176 return errors.New("tls: server selected an invalid version after a HelloRetryRequest")
177 }
178
179 if hs.serverHello.vers != VersionTLS12 {
180 c.sendAlert(alertIllegalParameter)
181 return errors.New("tls: server sent an incorrect legacy version")
182 }
183
184 if hs.serverHello.ocspStapling ||
185 hs.serverHello.ticketSupported ||
186 hs.serverHello.extendedMasterSecret ||
187 hs.serverHello.secureRenegotiationSupported ||
188 len(hs.serverHello.secureRenegotiation) != 0 ||
189 len(hs.serverHello.alpnProtocol) != 0 ||
190 len(hs.serverHello.scts) != 0 {
191 c.sendAlert(alertUnsupportedExtension)
192 return errors.New("tls: server sent a ServerHello extension forbidden in TLS 1.3")
193 }
194
195 if !bytes.Equal(hs.hello.sessionId, hs.serverHello.sessionId) {
196 c.sendAlert(alertIllegalParameter)
197 return errors.New("tls: server did not echo the legacy session ID")
198 }
199
200 if hs.serverHello.compressionMethod != compressionNone {
201 c.sendAlert(alertIllegalParameter)
202 return errors.New("tls: server selected unsupported compression format")
203 }
204
205 selectedSuite := mutualCipherSuiteTLS13(hs.hello.cipherSuites, hs.serverHello.cipherSuite)
206 if hs.suite != nil && selectedSuite != hs.suite {
207 c.sendAlert(alertIllegalParameter)
208 return errors.New("tls: server changed cipher suite after a HelloRetryRequest")
209 }
210 if selectedSuite == nil {
211 c.sendAlert(alertIllegalParameter)
212 return errors.New("tls: server chose an unconfigured cipher suite")
213 }
214 hs.suite = selectedSuite
215 c.cipherSuite = hs.suite.id
216
217 return nil
218 }
219
220
221
222 func (hs *clientHandshakeStateTLS13) sendDummyChangeCipherSpec() error {
223 if hs.c.quic != nil {
224 return nil
225 }
226 if hs.sentDummyCCS {
227 return nil
228 }
229 hs.sentDummyCCS = true
230
231 return hs.c.writeChangeCipherRecord()
232 }
233
234
235
236 func (hs *clientHandshakeStateTLS13) processHelloRetryRequest() error {
237 c := hs.c
238
239
240
241
242 chHash := hs.transcript.Sum(nil)
243 hs.transcript.Reset()
244 hs.transcript.Write([]byte{typeMessageHash, 0, 0, uint8(len(chHash))})
245 hs.transcript.Write(chHash)
246 if err := transcriptMsg(hs.serverHello, hs.transcript); err != nil {
247 return err
248 }
249
250 var isInnerHello bool
251 hello := hs.hello
252 if hs.echContext != nil {
253 chHash = hs.echContext.innerTranscript.Sum(nil)
254 hs.echContext.innerTranscript.Reset()
255 hs.echContext.innerTranscript.Write([]byte{typeMessageHash, 0, 0, uint8(len(chHash))})
256 hs.echContext.innerTranscript.Write(chHash)
257
258 if hs.serverHello.encryptedClientHello != nil {
259 if len(hs.serverHello.encryptedClientHello) != 8 {
260 hs.c.sendAlert(alertDecodeError)
261 return errors.New("tls: malformed encrypted client hello extension")
262 }
263
264 confTranscript := cloneHash(hs.echContext.innerTranscript, hs.suite.hash)
265 hrrHello := make([]byte, len(hs.serverHello.original))
266 copy(hrrHello, hs.serverHello.original)
267 hrrHello = bytes.Replace(hrrHello, hs.serverHello.encryptedClientHello, make([]byte, 8), 1)
268 confTranscript.Write(hrrHello)
269 acceptConfirmation := hs.suite.expandLabel(
270 hs.suite.extract(hs.echContext.innerHello.random, nil),
271 "hrr ech accept confirmation",
272 confTranscript.Sum(nil),
273 8,
274 )
275 if subtle.ConstantTimeCompare(acceptConfirmation, hs.serverHello.encryptedClientHello) == 1 {
276 hello = hs.echContext.innerHello
277 c.serverName = c.config.ServerName
278 isInnerHello = true
279 c.echAccepted = true
280 }
281 }
282
283 if err := transcriptMsg(hs.serverHello, hs.echContext.innerTranscript); err != nil {
284 return err
285 }
286 } else if hs.serverHello.encryptedClientHello != nil {
287
288 c.sendAlert(alertUnsupportedExtension)
289 return errors.New("tls: unexpected ECH extension in serverHello")
290 }
291
292
293
294
295 if hs.serverHello.selectedGroup == 0 && hs.serverHello.cookie == nil {
296 c.sendAlert(alertIllegalParameter)
297 return errors.New("tls: server sent an unnecessary HelloRetryRequest message")
298 }
299
300 if hs.serverHello.cookie != nil {
301 hello.cookie = hs.serverHello.cookie
302 }
303
304 if hs.serverHello.serverShare.group != 0 {
305 c.sendAlert(alertDecodeError)
306 return errors.New("tls: received malformed key_share extension")
307 }
308
309
310
311
312 if curveID := hs.serverHello.selectedGroup; curveID != 0 {
313 if !slices.Contains(hello.supportedCurves, curveID) {
314 c.sendAlert(alertIllegalParameter)
315 return errors.New("tls: server selected unsupported group")
316 }
317 if slices.ContainsFunc(hs.hello.keyShares, func(ks keyShare) bool {
318 return ks.group == curveID
319 }) {
320 c.sendAlert(alertIllegalParameter)
321 return errors.New("tls: server sent an unnecessary HelloRetryRequest key_share")
322 }
323
324
325
326
327
328
329 if _, ok := curveForCurveID(curveID); !ok {
330 c.sendAlert(alertInternalError)
331 return errors.New("tls: CurvePreferences includes unsupported curve")
332 }
333 key, err := generateECDHEKey(c.config.rand(), curveID)
334 if err != nil {
335 c.sendAlert(alertInternalError)
336 return err
337 }
338 hs.keyShareKeys = &keySharePrivateKeys{curveID: curveID, ecdhe: key}
339 hello.keyShares = []keyShare{{group: curveID, data: key.PublicKey().Bytes()}}
340 }
341
342 if len(hello.pskIdentities) > 0 {
343 pskSuite := cipherSuiteTLS13ByID(hs.session.cipherSuite)
344 if pskSuite == nil {
345 return c.sendAlert(alertInternalError)
346 }
347 if pskSuite.hash == hs.suite.hash {
348
349 ticketAge := c.config.time().Sub(time.Unix(int64(hs.session.createdAt), 0))
350 hello.pskIdentities[0].obfuscatedTicketAge = uint32(ticketAge/time.Millisecond) + hs.session.ageAdd
351
352 transcript := hs.suite.hash.New()
353 transcript.Write([]byte{typeMessageHash, 0, 0, uint8(len(chHash))})
354 transcript.Write(chHash)
355 if err := transcriptMsg(hs.serverHello, transcript); err != nil {
356 return err
357 }
358
359 if err := computeAndUpdatePSK(hello, hs.binderKey, transcript, hs.suite.finishedHash); err != nil {
360 return err
361 }
362 } else {
363
364 hello.pskIdentities = nil
365 hello.pskBinders = nil
366 }
367 }
368
369 if hello.earlyData {
370 hello.earlyData = false
371 c.quicRejectedEarlyData()
372 }
373
374 if isInnerHello {
375
376
377
378
379 hs.hello.keyShares = hello.keyShares
380 hs.echContext.innerHello = hello
381 if err := transcriptMsg(hs.echContext.innerHello, hs.echContext.innerTranscript); err != nil {
382 return err
383 }
384
385 if err := computeAndUpdateOuterECHExtension(hs.hello, hs.echContext.innerHello, hs.echContext, false); err != nil {
386 return err
387 }
388 } else {
389 hs.hello = hello
390 }
391
392 if _, err := hs.c.writeHandshakeRecord(hs.hello, hs.transcript); err != nil {
393 return err
394 }
395
396
397 msg, err := c.readHandshake(nil)
398 if err != nil {
399 return err
400 }
401
402 serverHello, ok := msg.(*serverHelloMsg)
403 if !ok {
404 c.sendAlert(alertUnexpectedMessage)
405 return unexpectedMessageError(serverHello, msg)
406 }
407 hs.serverHello = serverHello
408
409 if err := hs.checkServerHelloOrHRR(); err != nil {
410 return err
411 }
412
413 c.didHRR = true
414 return nil
415 }
416
417 func (hs *clientHandshakeStateTLS13) processServerHello() error {
418 c := hs.c
419
420 if bytes.Equal(hs.serverHello.random, helloRetryRequestRandom) {
421 c.sendAlert(alertUnexpectedMessage)
422 return errors.New("tls: server sent two HelloRetryRequest messages")
423 }
424
425 if len(hs.serverHello.cookie) != 0 {
426 c.sendAlert(alertUnsupportedExtension)
427 return errors.New("tls: server sent a cookie in a normal ServerHello")
428 }
429
430 if hs.serverHello.selectedGroup != 0 {
431 c.sendAlert(alertDecodeError)
432 return errors.New("tls: malformed key_share extension")
433 }
434
435 if hs.serverHello.serverShare.group == 0 {
436 c.sendAlert(alertIllegalParameter)
437 return errors.New("tls: server did not send a key share")
438 }
439 if !slices.ContainsFunc(hs.hello.keyShares, func(ks keyShare) bool {
440 return ks.group == hs.serverHello.serverShare.group
441 }) {
442 c.sendAlert(alertIllegalParameter)
443 return errors.New("tls: server selected unsupported group")
444 }
445
446 if !hs.serverHello.selectedIdentityPresent {
447 return nil
448 }
449
450 if int(hs.serverHello.selectedIdentity) >= len(hs.hello.pskIdentities) {
451 c.sendAlert(alertIllegalParameter)
452 return errors.New("tls: server selected an invalid PSK")
453 }
454
455 if len(hs.hello.pskIdentities) != 1 || hs.session == nil {
456 return c.sendAlert(alertInternalError)
457 }
458 pskSuite := cipherSuiteTLS13ByID(hs.session.cipherSuite)
459 if pskSuite == nil {
460 return c.sendAlert(alertInternalError)
461 }
462 if pskSuite.hash != hs.suite.hash {
463 c.sendAlert(alertIllegalParameter)
464 return errors.New("tls: server selected an invalid PSK and cipher suite pair")
465 }
466
467 hs.usingPSK = true
468 c.didResume = true
469 c.peerCertificates = hs.session.peerCertificates
470 c.activeCertHandles = hs.session.activeCertHandles
471 c.verifiedChains = hs.session.verifiedChains
472 c.ocspResponse = hs.session.ocspResponse
473 c.scts = hs.session.scts
474 return nil
475 }
476
477 func (hs *clientHandshakeStateTLS13) establishHandshakeKeys() error {
478 c := hs.c
479
480 ecdhePeerData := hs.serverHello.serverShare.data
481 if hs.serverHello.serverShare.group == x25519Kyber768Draft00 {
482 if len(ecdhePeerData) != x25519PublicKeySize+mlkem768.CiphertextSize {
483 c.sendAlert(alertIllegalParameter)
484 return errors.New("tls: invalid server key share")
485 }
486 ecdhePeerData = hs.serverHello.serverShare.data[:x25519PublicKeySize]
487 }
488 peerKey, err := hs.keyShareKeys.ecdhe.Curve().NewPublicKey(ecdhePeerData)
489 if err != nil {
490 c.sendAlert(alertIllegalParameter)
491 return errors.New("tls: invalid server key share")
492 }
493 sharedKey, err := hs.keyShareKeys.ecdhe.ECDH(peerKey)
494 if err != nil {
495 c.sendAlert(alertIllegalParameter)
496 return errors.New("tls: invalid server key share")
497 }
498 if hs.serverHello.serverShare.group == x25519Kyber768Draft00 {
499 if hs.keyShareKeys.kyber == nil {
500 return c.sendAlert(alertInternalError)
501 }
502 ciphertext := hs.serverHello.serverShare.data[x25519PublicKeySize:]
503 kyberShared, err := kyberDecapsulate(hs.keyShareKeys.kyber, ciphertext)
504 if err != nil {
505 c.sendAlert(alertIllegalParameter)
506 return errors.New("tls: invalid Kyber server key share")
507 }
508 sharedKey = append(sharedKey, kyberShared...)
509 }
510 c.curveID = hs.serverHello.serverShare.group
511
512 earlySecret := hs.earlySecret
513 if !hs.usingPSK {
514 earlySecret = hs.suite.extract(nil, nil)
515 }
516
517 handshakeSecret := hs.suite.extract(sharedKey,
518 hs.suite.deriveSecret(earlySecret, "derived", nil))
519
520 clientSecret := hs.suite.deriveSecret(handshakeSecret,
521 clientHandshakeTrafficLabel, hs.transcript)
522 c.out.setTrafficSecret(hs.suite, QUICEncryptionLevelHandshake, clientSecret)
523 serverSecret := hs.suite.deriveSecret(handshakeSecret,
524 serverHandshakeTrafficLabel, hs.transcript)
525 c.in.setTrafficSecret(hs.suite, QUICEncryptionLevelHandshake, serverSecret)
526
527 if c.quic != nil {
528 if c.hand.Len() != 0 {
529 c.sendAlert(alertUnexpectedMessage)
530 }
531 c.quicSetWriteSecret(QUICEncryptionLevelHandshake, hs.suite.id, clientSecret)
532 c.quicSetReadSecret(QUICEncryptionLevelHandshake, hs.suite.id, serverSecret)
533 }
534
535 err = c.config.writeKeyLog(keyLogLabelClientHandshake, hs.hello.random, clientSecret)
536 if err != nil {
537 c.sendAlert(alertInternalError)
538 return err
539 }
540 err = c.config.writeKeyLog(keyLogLabelServerHandshake, hs.hello.random, serverSecret)
541 if err != nil {
542 c.sendAlert(alertInternalError)
543 return err
544 }
545
546 hs.masterSecret = hs.suite.extract(nil,
547 hs.suite.deriveSecret(handshakeSecret, "derived", nil))
548
549 return nil
550 }
551
552 func (hs *clientHandshakeStateTLS13) readServerParameters() error {
553 c := hs.c
554
555 msg, err := c.readHandshake(hs.transcript)
556 if err != nil {
557 return err
558 }
559
560 encryptedExtensions, ok := msg.(*encryptedExtensionsMsg)
561 if !ok {
562 c.sendAlert(alertUnexpectedMessage)
563 return unexpectedMessageError(encryptedExtensions, msg)
564 }
565
566 if err := checkALPN(hs.hello.alpnProtocols, encryptedExtensions.alpnProtocol, c.quic != nil); err != nil {
567
568
569
570
571 c.sendAlert(alertNoApplicationProtocol)
572 return err
573 }
574 c.clientProtocol = encryptedExtensions.alpnProtocol
575
576 if c.quic != nil {
577 if encryptedExtensions.quicTransportParameters == nil {
578
579 c.sendAlert(alertMissingExtension)
580 return errors.New("tls: server did not send a quic_transport_parameters extension")
581 }
582 c.quicSetTransportParameters(encryptedExtensions.quicTransportParameters)
583 } else {
584 if encryptedExtensions.quicTransportParameters != nil {
585 c.sendAlert(alertUnsupportedExtension)
586 return errors.New("tls: server sent an unexpected quic_transport_parameters extension")
587 }
588 }
589
590 if !hs.hello.earlyData && encryptedExtensions.earlyData {
591 c.sendAlert(alertUnsupportedExtension)
592 return errors.New("tls: server sent an unexpected early_data extension")
593 }
594 if hs.hello.earlyData && !encryptedExtensions.earlyData {
595 c.quicRejectedEarlyData()
596 }
597 if encryptedExtensions.earlyData {
598 if hs.session.cipherSuite != c.cipherSuite {
599 c.sendAlert(alertHandshakeFailure)
600 return errors.New("tls: server accepted 0-RTT with the wrong cipher suite")
601 }
602 if hs.session.alpnProtocol != c.clientProtocol {
603 c.sendAlert(alertHandshakeFailure)
604 return errors.New("tls: server accepted 0-RTT with the wrong ALPN")
605 }
606 }
607 if hs.echContext != nil && !hs.echContext.echRejected && encryptedExtensions.echRetryConfigs != nil {
608 c.sendAlert(alertUnsupportedExtension)
609 return errors.New("tls: server sent ECH retry configs after accepting ECH")
610 }
611
612 return nil
613 }
614
615 func (hs *clientHandshakeStateTLS13) readServerCertificate() error {
616 c := hs.c
617
618
619
620 if hs.usingPSK {
621
622
623
624 if c.config.VerifyConnection != nil {
625 if err := c.config.VerifyConnection(c.connectionStateLocked()); err != nil {
626 c.sendAlert(alertBadCertificate)
627 return err
628 }
629 }
630 return nil
631 }
632
633 msg, err := c.readHandshake(hs.transcript)
634 if err != nil {
635 return err
636 }
637
638 certReq, ok := msg.(*certificateRequestMsgTLS13)
639 if ok {
640 hs.certReq = certReq
641
642 msg, err = c.readHandshake(hs.transcript)
643 if err != nil {
644 return err
645 }
646 }
647
648 certMsg, ok := msg.(*certificateMsgTLS13)
649 if !ok {
650 c.sendAlert(alertUnexpectedMessage)
651 return unexpectedMessageError(certMsg, msg)
652 }
653 if len(certMsg.certificate.Certificate) == 0 {
654 c.sendAlert(alertDecodeError)
655 return errors.New("tls: received empty certificates message")
656 }
657
658 c.scts = certMsg.certificate.SignedCertificateTimestamps
659 c.ocspResponse = certMsg.certificate.OCSPStaple
660
661 if err := c.verifyServerCertificate(certMsg.certificate.Certificate); err != nil {
662 return err
663 }
664
665
666
667
668 msg, err = c.readHandshake(nil)
669 if err != nil {
670 return err
671 }
672
673 certVerify, ok := msg.(*certificateVerifyMsg)
674 if !ok {
675 c.sendAlert(alertUnexpectedMessage)
676 return unexpectedMessageError(certVerify, msg)
677 }
678
679
680 if !isSupportedSignatureAlgorithm(certVerify.signatureAlgorithm, supportedSignatureAlgorithms()) {
681 c.sendAlert(alertIllegalParameter)
682 return errors.New("tls: certificate used with invalid signature algorithm")
683 }
684 sigType, sigHash, err := typeAndHashFromSignatureScheme(certVerify.signatureAlgorithm)
685 if err != nil {
686 return c.sendAlert(alertInternalError)
687 }
688 if sigType == signaturePKCS1v15 || sigHash == crypto.SHA1 {
689 c.sendAlert(alertIllegalParameter)
690 return errors.New("tls: certificate used with invalid signature algorithm")
691 }
692 signed := signedMessage(sigHash, serverSignatureContext, hs.transcript)
693 if err := verifyHandshakeSignature(sigType, c.peerCertificates[0].PublicKey,
694 sigHash, signed, certVerify.signature); err != nil {
695 c.sendAlert(alertDecryptError)
696 return errors.New("tls: invalid signature by the server certificate: " + err.Error())
697 }
698
699 if err := transcriptMsg(certVerify, hs.transcript); err != nil {
700 return err
701 }
702
703 return nil
704 }
705
706 func (hs *clientHandshakeStateTLS13) readServerFinished() error {
707 c := hs.c
708
709
710
711
712 msg, err := c.readHandshake(nil)
713 if err != nil {
714 return err
715 }
716
717 finished, ok := msg.(*finishedMsg)
718 if !ok {
719 c.sendAlert(alertUnexpectedMessage)
720 return unexpectedMessageError(finished, msg)
721 }
722
723 expectedMAC := hs.suite.finishedHash(c.in.trafficSecret, hs.transcript)
724 if !hmac.Equal(expectedMAC, finished.verifyData) {
725 c.sendAlert(alertDecryptError)
726 return errors.New("tls: invalid server finished hash")
727 }
728
729 if err := transcriptMsg(finished, hs.transcript); err != nil {
730 return err
731 }
732
733
734
735 hs.trafficSecret = hs.suite.deriveSecret(hs.masterSecret,
736 clientApplicationTrafficLabel, hs.transcript)
737 serverSecret := hs.suite.deriveSecret(hs.masterSecret,
738 serverApplicationTrafficLabel, hs.transcript)
739 c.in.setTrafficSecret(hs.suite, QUICEncryptionLevelApplication, serverSecret)
740
741 err = c.config.writeKeyLog(keyLogLabelClientTraffic, hs.hello.random, hs.trafficSecret)
742 if err != nil {
743 c.sendAlert(alertInternalError)
744 return err
745 }
746 err = c.config.writeKeyLog(keyLogLabelServerTraffic, hs.hello.random, serverSecret)
747 if err != nil {
748 c.sendAlert(alertInternalError)
749 return err
750 }
751
752 c.ekm = hs.suite.exportKeyingMaterial(hs.masterSecret, hs.transcript)
753
754 return nil
755 }
756
757 func (hs *clientHandshakeStateTLS13) sendClientCertificate() error {
758 c := hs.c
759
760 if hs.certReq == nil {
761 return nil
762 }
763
764 if hs.echContext != nil && hs.echContext.echRejected {
765 if _, err := hs.c.writeHandshakeRecord(&certificateMsgTLS13{}, hs.transcript); err != nil {
766 return err
767 }
768 return nil
769 }
770
771 cert, err := c.getClientCertificate(&CertificateRequestInfo{
772 AcceptableCAs: hs.certReq.certificateAuthorities,
773 SignatureSchemes: hs.certReq.supportedSignatureAlgorithms,
774 Version: c.vers,
775 ctx: hs.ctx,
776 })
777 if err != nil {
778 return err
779 }
780
781 certMsg := new(certificateMsgTLS13)
782
783 certMsg.certificate = *cert
784 certMsg.scts = hs.certReq.scts && len(cert.SignedCertificateTimestamps) > 0
785 certMsg.ocspStapling = hs.certReq.ocspStapling && len(cert.OCSPStaple) > 0
786
787 if _, err := hs.c.writeHandshakeRecord(certMsg, hs.transcript); err != nil {
788 return err
789 }
790
791
792 if len(cert.Certificate) == 0 {
793 return nil
794 }
795
796 certVerifyMsg := new(certificateVerifyMsg)
797 certVerifyMsg.hasSignatureAlgorithm = true
798
799 certVerifyMsg.signatureAlgorithm, err = selectSignatureScheme(c.vers, cert, hs.certReq.supportedSignatureAlgorithms)
800 if err != nil {
801
802
803 c.sendAlert(alertHandshakeFailure)
804 return err
805 }
806
807 sigType, sigHash, err := typeAndHashFromSignatureScheme(certVerifyMsg.signatureAlgorithm)
808 if err != nil {
809 return c.sendAlert(alertInternalError)
810 }
811
812 signed := signedMessage(sigHash, clientSignatureContext, hs.transcript)
813 signOpts := crypto.SignerOpts(sigHash)
814 if sigType == signatureRSAPSS {
815 signOpts = &rsa.PSSOptions{SaltLength: rsa.PSSSaltLengthEqualsHash, Hash: sigHash}
816 }
817 sig, err := cert.PrivateKey.(crypto.Signer).Sign(c.config.rand(), signed, signOpts)
818 if err != nil {
819 c.sendAlert(alertInternalError)
820 return errors.New("tls: failed to sign handshake: " + err.Error())
821 }
822 certVerifyMsg.signature = sig
823
824 if _, err := hs.c.writeHandshakeRecord(certVerifyMsg, hs.transcript); err != nil {
825 return err
826 }
827
828 return nil
829 }
830
831 func (hs *clientHandshakeStateTLS13) sendClientFinished() error {
832 c := hs.c
833
834 finished := &finishedMsg{
835 verifyData: hs.suite.finishedHash(c.out.trafficSecret, hs.transcript),
836 }
837
838 if _, err := hs.c.writeHandshakeRecord(finished, hs.transcript); err != nil {
839 return err
840 }
841
842 c.out.setTrafficSecret(hs.suite, QUICEncryptionLevelApplication, hs.trafficSecret)
843
844 if !c.config.SessionTicketsDisabled && c.config.ClientSessionCache != nil {
845 c.resumptionSecret = hs.suite.deriveSecret(hs.masterSecret,
846 resumptionLabel, hs.transcript)
847 }
848
849 if c.quic != nil {
850 if c.hand.Len() != 0 {
851 c.sendAlert(alertUnexpectedMessage)
852 }
853 c.quicSetWriteSecret(QUICEncryptionLevelApplication, hs.suite.id, hs.trafficSecret)
854 }
855
856 return nil
857 }
858
859 func (c *Conn) handleNewSessionTicket(msg *newSessionTicketMsgTLS13) error {
860 if !c.isClient {
861 c.sendAlert(alertUnexpectedMessage)
862 return errors.New("tls: received new session ticket from a client")
863 }
864
865 if c.config.SessionTicketsDisabled || c.config.ClientSessionCache == nil {
866 return nil
867 }
868
869
870 if msg.lifetime == 0 {
871 return nil
872 }
873 lifetime := time.Duration(msg.lifetime) * time.Second
874 if lifetime > maxSessionTicketLifetime {
875 c.sendAlert(alertIllegalParameter)
876 return errors.New("tls: received a session ticket with invalid lifetime")
877 }
878
879
880 if c.quic != nil && msg.maxEarlyData != 0 && msg.maxEarlyData != 0xffffffff {
881 c.sendAlert(alertIllegalParameter)
882 return errors.New("tls: invalid early data for QUIC connection")
883 }
884
885 cipherSuite := cipherSuiteTLS13ByID(c.cipherSuite)
886 if cipherSuite == nil || c.resumptionSecret == nil {
887 return c.sendAlert(alertInternalError)
888 }
889
890 psk := cipherSuite.expandLabel(c.resumptionSecret, "resumption",
891 msg.nonce, cipherSuite.hash.Size())
892
893 session := c.sessionState()
894 session.secret = psk
895 session.useBy = uint64(c.config.time().Add(lifetime).Unix())
896 session.ageAdd = msg.ageAdd
897 session.EarlyData = c.quic != nil && msg.maxEarlyData == 0xffffffff
898 session.ticket = msg.label
899 if c.quic != nil && c.quic.enableSessionEvents {
900 c.quicStoreSession(session)
901 return nil
902 }
903 cs := &ClientSessionState{session: session}
904 if cacheKey := c.clientSessionCacheKey(); cacheKey != "" {
905 c.config.ClientSessionCache.Put(cacheKey, cs)
906 }
907
908 return nil
909 }
910
View as plain text