Source file
src/crypto/tls/handshake_server_tls13.go
1
2
3
4
5 package tls
6
7 import (
8 "bytes"
9 "context"
10 "crypto"
11 "crypto/hkdf"
12 "crypto/hmac"
13 "crypto/hpke"
14 "crypto/internal/fips140/tls13"
15 "crypto/rsa"
16 "crypto/tls/internal/fips140tls"
17 "errors"
18 "fmt"
19 "hash"
20 "internal/byteorder"
21 "io"
22 "slices"
23 "sort"
24 "time"
25 )
26
27
28
29
30 const maxClientPSKIdentities = 5
31
32 type echServerContext struct {
33 hpkeContext *hpke.Recipient
34 configID uint8
35 ciphersuite echCipher
36 transcript hash.Hash
37
38
39
40
41 inner bool
42 }
43
44 type serverHandshakeStateTLS13 struct {
45 c *Conn
46 ctx context.Context
47 clientHello *clientHelloMsg
48 hello *serverHelloMsg
49 sentDummyCCS bool
50 usingPSK bool
51 earlyData bool
52 suite *cipherSuiteTLS13
53 cert *Certificate
54 sigAlg SignatureScheme
55 earlySecret *tls13.EarlySecret
56 sharedKey []byte
57 handshakeSecret *tls13.HandshakeSecret
58 masterSecret *tls13.MasterSecret
59 trafficSecret []byte
60 transcript hash.Hash
61 clientFinished []byte
62 echContext *echServerContext
63 }
64
65 func (hs *serverHandshakeStateTLS13) handshake() error {
66 c := hs.c
67
68
69 if err := hs.processClientHello(); err != nil {
70 return err
71 }
72 if err := hs.checkForResumption(); err != nil {
73 return err
74 }
75 if err := hs.pickCertificate(); err != nil {
76 return err
77 }
78 c.buffering = true
79 if err := hs.sendServerParameters(); err != nil {
80 return err
81 }
82 if err := hs.sendServerCertificate(); err != nil {
83 return err
84 }
85 if err := hs.sendServerFinished(); err != nil {
86 return err
87 }
88
89
90
91 if _, err := c.flush(); err != nil {
92 return err
93 }
94 if err := hs.readClientCertificate(); err != nil {
95 return err
96 }
97 if err := hs.readClientFinished(); err != nil {
98 return err
99 }
100
101 c.isHandshakeComplete.Store(true)
102
103 return nil
104 }
105
106 func (hs *serverHandshakeStateTLS13) processClientHello() error {
107 c := hs.c
108
109 hs.hello = new(serverHelloMsg)
110
111
112
113 hs.hello.vers = VersionTLS12
114 hs.hello.supportedVersion = c.vers
115
116 if len(hs.clientHello.supportedVersions) == 0 {
117 c.sendAlert(alertIllegalParameter)
118 return errors.New("tls: client used the legacy version field to negotiate TLS 1.3")
119 }
120
121
122
123
124
125
126
127
128
129
130 for _, id := range hs.clientHello.cipherSuites {
131 if id == TLS_FALLBACK_SCSV {
132
133
134 if c.vers < c.config.maxSupportedVersion(roleServer) {
135 c.sendAlert(alertInappropriateFallback)
136 return errors.New("tls: client using inappropriate protocol fallback")
137 }
138 break
139 }
140 }
141
142 if len(hs.clientHello.compressionMethods) != 1 ||
143 hs.clientHello.compressionMethods[0] != compressionNone {
144 c.sendAlert(alertIllegalParameter)
145 return errors.New("tls: TLS 1.3 client supports illegal compression methods")
146 }
147
148 hs.hello.random = make([]byte, 32)
149 if _, err := io.ReadFull(c.config.rand(), hs.hello.random); err != nil {
150 c.sendAlert(alertInternalError)
151 return err
152 }
153
154 if len(hs.clientHello.secureRenegotiation) != 0 {
155 c.sendAlert(alertHandshakeFailure)
156 return errors.New("tls: initial handshake had non-empty renegotiation extension")
157 }
158
159 if hs.clientHello.earlyData && c.quic != nil {
160 if len(hs.clientHello.pskIdentities) == 0 {
161 c.sendAlert(alertIllegalParameter)
162 return errors.New("tls: early_data without pre_shared_key")
163 }
164 } else if hs.clientHello.earlyData {
165
166
167
168
169
170
171 c.sendAlert(alertUnsupportedExtension)
172 return errors.New("tls: client sent unexpected early data")
173 }
174
175 hs.hello.sessionId = hs.clientHello.sessionId
176 hs.hello.compressionMethod = compressionNone
177
178 preferenceList := defaultCipherSuitesTLS13
179 if !hasAESGCMHardwareSupport || !isAESGCMPreferred(hs.clientHello.cipherSuites) {
180 preferenceList = defaultCipherSuitesTLS13NoAES
181 }
182 if fips140tls.Required() {
183 preferenceList = allowedCipherSuitesTLS13FIPS
184 }
185 for _, suiteID := range preferenceList {
186 hs.suite = mutualCipherSuiteTLS13(hs.clientHello.cipherSuites, suiteID)
187 if hs.suite != nil {
188 break
189 }
190 }
191 if hs.suite == nil {
192 c.sendAlert(alertHandshakeFailure)
193 return fmt.Errorf("tls: no cipher suite supported by both client and server; client offered: %x",
194 hs.clientHello.cipherSuites)
195 }
196 c.cipherSuite = hs.suite.id
197 hs.hello.cipherSuite = hs.suite.id
198 hs.transcript = hs.suite.hash.New()
199
200
201
202
203
204
205
206
207
208 preferredGroups := c.config.curvePreferences(c.vers)
209 preferredGroups = slices.DeleteFunc(preferredGroups, func(group CurveID) bool {
210 return !slices.Contains(hs.clientHello.supportedCurves, group)
211 })
212 if len(preferredGroups) == 0 {
213 c.sendAlert(alertHandshakeFailure)
214 return errors.New("tls: no key exchanges supported by both client and server")
215 }
216 hasKeyShare := func(group CurveID) bool {
217 for _, ks := range hs.clientHello.keyShares {
218 if ks.group == group {
219 return true
220 }
221 }
222 return false
223 }
224 sort.SliceStable(preferredGroups, func(i, j int) bool {
225 return hasKeyShare(preferredGroups[i]) && !hasKeyShare(preferredGroups[j])
226 })
227 sort.SliceStable(preferredGroups, func(i, j int) bool {
228 return isPQKeyExchange(preferredGroups[i]) && !isPQKeyExchange(preferredGroups[j])
229 })
230 selectedGroup := preferredGroups[0]
231
232 var clientKeyShare *keyShare
233 for _, ks := range hs.clientHello.keyShares {
234 if ks.group == selectedGroup {
235 clientKeyShare = &ks
236 break
237 }
238 }
239 if clientKeyShare == nil {
240 ks, err := hs.doHelloRetryRequest(selectedGroup)
241 if err != nil {
242 return err
243 }
244 clientKeyShare = ks
245 }
246 c.curveID = selectedGroup
247
248 ke, err := keyExchangeForCurveID(selectedGroup)
249 if err != nil {
250 c.sendAlert(alertInternalError)
251 return errors.New("tls: CurvePreferences includes unsupported curve")
252 }
253 hs.sharedKey, hs.hello.serverShare, err = ke.serverSharedSecret(c.config.rand(), clientKeyShare.data)
254 if err != nil {
255 c.sendAlert(alertIllegalParameter)
256 return errors.New("tls: invalid client key share")
257 }
258
259 selectedProto, err := negotiateALPN(c.config.NextProtos, hs.clientHello.alpnProtocols, c.quic != nil)
260 if err != nil {
261 c.sendAlert(alertNoApplicationProtocol)
262 return err
263 }
264 c.clientProtocol = selectedProto
265
266 if c.quic != nil {
267
268 for _, v := range hs.clientHello.supportedVersions {
269 if v < VersionTLS13 {
270 c.sendAlert(alertProtocolVersion)
271 return errors.New("tls: client offered TLS version older than TLS 1.3")
272 }
273 }
274
275 if hs.clientHello.quicTransportParameters == nil {
276 c.sendAlert(alertMissingExtension)
277 return errors.New("tls: client did not send a quic_transport_parameters extension")
278 }
279 c.quicSetTransportParameters(hs.clientHello.quicTransportParameters)
280 } else {
281 if hs.clientHello.quicTransportParameters != nil {
282 c.sendAlert(alertUnsupportedExtension)
283 return errors.New("tls: client sent an unexpected quic_transport_parameters extension")
284 }
285 }
286
287 c.serverName = hs.clientHello.serverName
288 return nil
289 }
290
291 func (hs *serverHandshakeStateTLS13) checkForResumption() error {
292 c := hs.c
293
294 if c.config.SessionTicketsDisabled {
295 return nil
296 }
297
298 modeOK := false
299 for _, mode := range hs.clientHello.pskModes {
300 if mode == pskModeDHE {
301 modeOK = true
302 break
303 }
304 }
305 if !modeOK {
306 return nil
307 }
308
309 if len(hs.clientHello.pskIdentities) != len(hs.clientHello.pskBinders) {
310 c.sendAlert(alertIllegalParameter)
311 return errors.New("tls: invalid or missing PSK binders")
312 }
313 if len(hs.clientHello.pskIdentities) == 0 {
314 return nil
315 }
316
317 for i, identity := range hs.clientHello.pskIdentities {
318 if i >= maxClientPSKIdentities {
319 break
320 }
321
322 var sessionState *SessionState
323 if c.config.UnwrapSession != nil {
324 var err error
325 sessionState, err = c.config.UnwrapSession(identity.label, c.connectionStateLocked())
326 if err != nil {
327 return err
328 }
329 if sessionState == nil {
330 continue
331 }
332 } else {
333 plaintext := c.config.decryptTicket(identity.label, c.ticketKeys)
334 if plaintext == nil {
335 continue
336 }
337 var err error
338 sessionState, err = ParseSessionState(plaintext)
339 if err != nil {
340 continue
341 }
342 }
343
344 if sessionState.version != VersionTLS13 {
345 continue
346 }
347
348 createdAt := time.Unix(int64(sessionState.createdAt), 0)
349 if c.config.time().Sub(createdAt) > maxSessionTicketLifetime {
350 continue
351 }
352
353 pskSuite := cipherSuiteTLS13ByID(sessionState.cipherSuite)
354 if pskSuite == nil || pskSuite.hash != hs.suite.hash {
355 continue
356 }
357
358
359
360
361 sessionHasClientCerts := len(sessionState.peerCertificates) != 0
362 needClientCerts := requiresClientCert(c.config.ClientAuth)
363 if needClientCerts && !sessionHasClientCerts {
364 continue
365 }
366 if sessionHasClientCerts && c.config.ClientAuth == NoClientCert {
367 continue
368 }
369 if sessionHasClientCerts && c.config.time().After(sessionState.peerCertificates[0].NotAfter) {
370 continue
371 }
372 if sessionHasClientCerts && c.config.ClientAuth >= VerifyClientCertIfGiven &&
373 len(sessionState.verifiedChains) == 0 {
374 continue
375 }
376
377 if c.quic != nil && c.quic.enableSessionEvents {
378 if err := c.quicResumeSession(sessionState); err != nil {
379 return err
380 }
381 }
382
383 hs.earlySecret = tls13.NewEarlySecret(hs.suite.hash.New, sessionState.secret)
384 binderKey := hs.earlySecret.ResumptionBinderKey()
385
386 transcript := cloneHash(hs.transcript, hs.suite.hash)
387 if transcript == nil {
388 c.sendAlert(alertInternalError)
389 return errors.New("tls: internal error: failed to clone hash")
390 }
391 clientHelloBytes, err := hs.clientHello.marshalWithoutBinders()
392 if err != nil {
393 c.sendAlert(alertInternalError)
394 return err
395 }
396 transcript.Write(clientHelloBytes)
397 pskBinder := hs.suite.finishedHash(binderKey, transcript)
398 if !hmac.Equal(hs.clientHello.pskBinders[i], pskBinder) {
399 c.sendAlert(alertDecryptError)
400 return errors.New("tls: invalid PSK binder")
401 }
402
403 if c.quic != nil && hs.clientHello.earlyData && i == 0 &&
404 sessionState.EarlyData && sessionState.cipherSuite == hs.suite.id &&
405 sessionState.alpnProtocol == c.clientProtocol {
406 hs.earlyData = true
407
408 transcript := hs.suite.hash.New()
409 if err := transcriptMsg(hs.clientHello, transcript); err != nil {
410 return err
411 }
412 earlyTrafficSecret := hs.earlySecret.ClientEarlyTrafficSecret(transcript)
413 c.quicSetReadSecret(QUICEncryptionLevelEarly, hs.suite.id, earlyTrafficSecret)
414 }
415
416 c.didResume = true
417 c.peerCertificates = sessionState.peerCertificates
418 c.ocspResponse = sessionState.ocspResponse
419 c.scts = sessionState.scts
420 c.verifiedChains = sessionState.verifiedChains
421
422 hs.hello.selectedIdentityPresent = true
423 hs.hello.selectedIdentity = uint16(i)
424 hs.usingPSK = true
425 return nil
426 }
427
428 return nil
429 }
430
431
432
433
434
435
436 func cloneHash(in hash.Hash, h crypto.Hash) hash.Hash {
437 if cloner, ok := in.(hash.Cloner); ok {
438 if out, err := cloner.Clone(); err == nil {
439 return out
440 }
441 }
442
443 type binaryMarshaler interface {
444 MarshalBinary() (data []byte, err error)
445 UnmarshalBinary(data []byte) error
446 }
447 marshaler, ok := in.(binaryMarshaler)
448 if !ok {
449 return nil
450 }
451 state, err := marshaler.MarshalBinary()
452 if err != nil {
453 return nil
454 }
455 out := h.New()
456 unmarshaler, ok := out.(binaryMarshaler)
457 if !ok {
458 return nil
459 }
460 if err := unmarshaler.UnmarshalBinary(state); err != nil {
461 return nil
462 }
463 return out
464 }
465
466 func (hs *serverHandshakeStateTLS13) pickCertificate() error {
467 c := hs.c
468
469
470 if hs.usingPSK {
471 return nil
472 }
473
474
475 if len(hs.clientHello.supportedSignatureAlgorithms) == 0 {
476 return c.sendAlert(alertMissingExtension)
477 }
478
479 certificate, err := c.config.getCertificate(clientHelloInfo(hs.ctx, c, hs.clientHello))
480 if err != nil {
481 if err == errNoCertificates {
482 c.sendAlert(alertUnrecognizedName)
483 } else {
484 c.sendAlert(alertInternalError)
485 }
486 return err
487 }
488 hs.sigAlg, err = selectSignatureScheme(c.vers, certificate, hs.clientHello.supportedSignatureAlgorithms)
489 if err != nil {
490
491
492 c.sendAlert(alertHandshakeFailure)
493 return err
494 }
495 hs.cert = certificate
496
497 return nil
498 }
499
500
501
502 func (hs *serverHandshakeStateTLS13) sendDummyChangeCipherSpec() error {
503 if hs.c.quic != nil {
504 return nil
505 }
506 if hs.sentDummyCCS {
507 return nil
508 }
509 hs.sentDummyCCS = true
510
511 return hs.c.writeChangeCipherRecord()
512 }
513
514 func (hs *serverHandshakeStateTLS13) doHelloRetryRequest(selectedGroup CurveID) (*keyShare, error) {
515 c := hs.c
516
517
518
519 if err := transcriptMsg(hs.clientHello, hs.transcript); err != nil {
520 return nil, err
521 }
522 chHash := hs.transcript.Sum(nil)
523 hs.transcript.Reset()
524 hs.transcript.Write([]byte{typeMessageHash, 0, 0, uint8(len(chHash))})
525 hs.transcript.Write(chHash)
526
527 helloRetryRequest := &serverHelloMsg{
528 vers: hs.hello.vers,
529 random: helloRetryRequestRandom,
530 sessionId: hs.hello.sessionId,
531 cipherSuite: hs.hello.cipherSuite,
532 compressionMethod: hs.hello.compressionMethod,
533 supportedVersion: hs.hello.supportedVersion,
534 selectedGroup: selectedGroup,
535 }
536
537 if hs.echContext != nil {
538
539 helloRetryRequest.encryptedClientHello = make([]byte, 8)
540 confTranscript := cloneHash(hs.transcript, hs.suite.hash)
541 if err := transcriptMsg(helloRetryRequest, confTranscript); err != nil {
542 return nil, err
543 }
544 h := hs.suite.hash.New
545 prf, err := hkdf.Extract(h, hs.clientHello.random, nil)
546 if err != nil {
547 c.sendAlert(alertInternalError)
548 return nil, err
549 }
550 acceptConfirmation := tls13.ExpandLabel(h, prf, "hrr ech accept confirmation", confTranscript.Sum(nil), 8)
551 helloRetryRequest.encryptedClientHello = acceptConfirmation
552 }
553
554 if _, err := hs.c.writeHandshakeRecord(helloRetryRequest, hs.transcript); err != nil {
555 return nil, err
556 }
557
558 if err := hs.sendDummyChangeCipherSpec(); err != nil {
559 return nil, err
560 }
561
562
563 msg, err := c.readHandshake(nil)
564 if err != nil {
565 return nil, err
566 }
567
568 clientHello, ok := msg.(*clientHelloMsg)
569 if !ok {
570 c.sendAlert(alertUnexpectedMessage)
571 return nil, unexpectedMessageError(clientHello, msg)
572 }
573
574 if hs.echContext != nil {
575 if len(clientHello.encryptedClientHello) == 0 {
576 c.sendAlert(alertMissingExtension)
577 return nil, errors.New("tls: second client hello missing encrypted client hello extension")
578 }
579
580 echType, echCiphersuite, configID, encap, payload, err := parseECHExt(clientHello.encryptedClientHello)
581 if err != nil {
582 c.sendAlert(alertDecodeError)
583 return nil, errors.New("tls: client sent invalid encrypted client hello extension")
584 }
585
586 if echType == outerECHExt && hs.echContext.inner || echType == innerECHExt && !hs.echContext.inner {
587 c.sendAlert(alertDecodeError)
588 return nil, errors.New("tls: unexpected switch in encrypted client hello extension type")
589 }
590
591 if echType == outerECHExt {
592 if echCiphersuite != hs.echContext.ciphersuite || configID != hs.echContext.configID || len(encap) != 0 {
593 c.sendAlert(alertIllegalParameter)
594 return nil, errors.New("tls: second client hello encrypted client hello extension does not match")
595 }
596
597 encodedInner, err := decryptECHPayload(hs.echContext.hpkeContext, clientHello.original, payload)
598 if err != nil {
599 c.sendAlert(alertDecryptError)
600 return nil, errors.New("tls: failed to decrypt second client hello encrypted client hello extension payload")
601 }
602
603 echInner, err := decodeInnerClientHello(clientHello, encodedInner)
604 if err != nil {
605 c.sendAlert(alertIllegalParameter)
606 return nil, errors.New("tls: client sent invalid encrypted client hello extension")
607 }
608
609 clientHello = echInner
610 }
611 }
612
613 if len(clientHello.keyShares) != 1 {
614 c.sendAlert(alertIllegalParameter)
615 return nil, errors.New("tls: client didn't send one key share in second ClientHello")
616 }
617 ks := &clientHello.keyShares[0]
618
619 if ks.group != selectedGroup {
620 c.sendAlert(alertIllegalParameter)
621 return nil, errors.New("tls: client sent unexpected key share in second ClientHello")
622 }
623
624 if clientHello.earlyData {
625 c.sendAlert(alertIllegalParameter)
626 return nil, errors.New("tls: client indicated early data in second ClientHello")
627 }
628
629 if illegalClientHelloChange(clientHello, hs.clientHello) {
630 c.sendAlert(alertIllegalParameter)
631 return nil, errors.New("tls: client illegally modified second ClientHello")
632 }
633
634 c.didHRR = true
635 hs.clientHello = clientHello
636 return ks, nil
637 }
638
639
640
641
642 func illegalClientHelloChange(ch, ch1 *clientHelloMsg) bool {
643 if len(ch.supportedVersions) != len(ch1.supportedVersions) ||
644 len(ch.cipherSuites) != len(ch1.cipherSuites) ||
645 len(ch.supportedCurves) != len(ch1.supportedCurves) ||
646 len(ch.supportedSignatureAlgorithms) != len(ch1.supportedSignatureAlgorithms) ||
647 len(ch.supportedSignatureAlgorithmsCert) != len(ch1.supportedSignatureAlgorithmsCert) ||
648 len(ch.alpnProtocols) != len(ch1.alpnProtocols) {
649 return true
650 }
651 for i := range ch.supportedVersions {
652 if ch.supportedVersions[i] != ch1.supportedVersions[i] {
653 return true
654 }
655 }
656 for i := range ch.cipherSuites {
657 if ch.cipherSuites[i] != ch1.cipherSuites[i] {
658 return true
659 }
660 }
661 for i := range ch.supportedCurves {
662 if ch.supportedCurves[i] != ch1.supportedCurves[i] {
663 return true
664 }
665 }
666 for i := range ch.supportedSignatureAlgorithms {
667 if ch.supportedSignatureAlgorithms[i] != ch1.supportedSignatureAlgorithms[i] {
668 return true
669 }
670 }
671 for i := range ch.supportedSignatureAlgorithmsCert {
672 if ch.supportedSignatureAlgorithmsCert[i] != ch1.supportedSignatureAlgorithmsCert[i] {
673 return true
674 }
675 }
676 for i := range ch.alpnProtocols {
677 if ch.alpnProtocols[i] != ch1.alpnProtocols[i] {
678 return true
679 }
680 }
681 return ch.vers != ch1.vers ||
682 !bytes.Equal(ch.random, ch1.random) ||
683 !bytes.Equal(ch.sessionId, ch1.sessionId) ||
684 !bytes.Equal(ch.compressionMethods, ch1.compressionMethods) ||
685 ch.serverName != ch1.serverName ||
686 ch.ocspStapling != ch1.ocspStapling ||
687 !bytes.Equal(ch.supportedPoints, ch1.supportedPoints) ||
688 ch.ticketSupported != ch1.ticketSupported ||
689 !bytes.Equal(ch.sessionTicket, ch1.sessionTicket) ||
690 ch.secureRenegotiationSupported != ch1.secureRenegotiationSupported ||
691 !bytes.Equal(ch.secureRenegotiation, ch1.secureRenegotiation) ||
692 ch.scts != ch1.scts ||
693 !bytes.Equal(ch.cookie, ch1.cookie) ||
694 !bytes.Equal(ch.pskModes, ch1.pskModes)
695 }
696
697 func (hs *serverHandshakeStateTLS13) sendServerParameters() error {
698 c := hs.c
699
700 if hs.echContext != nil {
701 copy(hs.hello.random[32-8:], make([]byte, 8))
702 echTranscript := cloneHash(hs.transcript, hs.suite.hash)
703 echTranscript.Write(hs.clientHello.original)
704 if err := transcriptMsg(hs.hello, echTranscript); err != nil {
705 return err
706 }
707
708 h := hs.suite.hash.New
709 prk, err := hkdf.Extract(h, hs.clientHello.random, nil)
710 if err != nil {
711 c.sendAlert(alertInternalError)
712 return err
713 }
714 acceptConfirmation := tls13.ExpandLabel(h, prk, "ech accept confirmation", echTranscript.Sum(nil), 8)
715 copy(hs.hello.random[32-8:], acceptConfirmation)
716 }
717
718 if err := transcriptMsg(hs.clientHello, hs.transcript); err != nil {
719 return err
720 }
721
722 if _, err := hs.c.writeHandshakeRecord(hs.hello, hs.transcript); err != nil {
723 return err
724 }
725
726 if err := hs.sendDummyChangeCipherSpec(); err != nil {
727 return err
728 }
729
730 earlySecret := hs.earlySecret
731 if earlySecret == nil {
732 earlySecret = tls13.NewEarlySecret(hs.suite.hash.New, nil)
733 }
734 hs.handshakeSecret = earlySecret.HandshakeSecret(hs.sharedKey)
735
736 clientSecret := hs.handshakeSecret.ClientHandshakeTrafficSecret(hs.transcript)
737 c.in.setTrafficSecret(hs.suite, QUICEncryptionLevelHandshake, clientSecret)
738 serverSecret := hs.handshakeSecret.ServerHandshakeTrafficSecret(hs.transcript)
739 c.out.setTrafficSecret(hs.suite, QUICEncryptionLevelHandshake, serverSecret)
740
741 if c.quic != nil {
742 if c.hand.Len() != 0 {
743 c.sendAlert(alertUnexpectedMessage)
744 }
745 c.quicSetWriteSecret(QUICEncryptionLevelHandshake, hs.suite.id, serverSecret)
746 c.quicSetReadSecret(QUICEncryptionLevelHandshake, hs.suite.id, clientSecret)
747 }
748
749 err := c.config.writeKeyLog(keyLogLabelClientHandshake, hs.clientHello.random, clientSecret)
750 if err != nil {
751 c.sendAlert(alertInternalError)
752 return err
753 }
754 err = c.config.writeKeyLog(keyLogLabelServerHandshake, hs.clientHello.random, serverSecret)
755 if err != nil {
756 c.sendAlert(alertInternalError)
757 return err
758 }
759
760 encryptedExtensions := new(encryptedExtensionsMsg)
761 encryptedExtensions.alpnProtocol = c.clientProtocol
762
763 if c.quic != nil {
764 p, err := c.quicGetTransportParameters()
765 if err != nil {
766 return err
767 }
768 encryptedExtensions.quicTransportParameters = p
769 encryptedExtensions.earlyData = hs.earlyData
770 }
771
772 if !hs.c.didResume && hs.clientHello.serverName != "" {
773 encryptedExtensions.serverNameAck = true
774 }
775
776
777
778 echKeys := hs.c.config.EncryptedClientHelloKeys
779 if hs.c.config.GetEncryptedClientHelloKeys != nil {
780 echKeys, err = hs.c.config.GetEncryptedClientHelloKeys(clientHelloInfo(hs.ctx, c, hs.clientHello))
781 if err != nil {
782 c.sendAlert(alertInternalError)
783 return err
784 }
785 }
786 if len(echKeys) > 0 && len(hs.clientHello.encryptedClientHello) > 0 && hs.echContext == nil {
787 encryptedExtensions.echRetryConfigs, err = buildRetryConfigList(echKeys)
788 if err != nil {
789 c.sendAlert(alertInternalError)
790 return err
791 }
792 }
793
794 if _, err := hs.c.writeHandshakeRecord(encryptedExtensions, hs.transcript); err != nil {
795 return err
796 }
797
798 return nil
799 }
800
801 func (hs *serverHandshakeStateTLS13) requestClientCert() bool {
802 return hs.c.config.ClientAuth >= RequestClientCert && !hs.usingPSK
803 }
804
805 func (hs *serverHandshakeStateTLS13) sendServerCertificate() error {
806 c := hs.c
807
808
809 if hs.usingPSK {
810 return nil
811 }
812
813 if hs.requestClientCert() {
814
815 certReq := new(certificateRequestMsgTLS13)
816 certReq.ocspStapling = true
817 certReq.scts = true
818 certReq.supportedSignatureAlgorithms = supportedSignatureAlgorithms(c.vers)
819 certReq.supportedSignatureAlgorithmsCert = supportedSignatureAlgorithmsCert()
820 if c.config.ClientCAs != nil {
821 certReq.certificateAuthorities = c.config.ClientCAs.Subjects()
822 }
823
824 if _, err := hs.c.writeHandshakeRecord(certReq, hs.transcript); err != nil {
825 return err
826 }
827 }
828
829 certMsg := new(certificateMsgTLS13)
830
831 certMsg.certificate = *hs.cert
832 certMsg.scts = hs.clientHello.scts && len(hs.cert.SignedCertificateTimestamps) > 0
833 certMsg.ocspStapling = hs.clientHello.ocspStapling && len(hs.cert.OCSPStaple) > 0
834
835 if _, err := hs.c.writeHandshakeRecord(certMsg, hs.transcript); err != nil {
836 return err
837 }
838
839 certVerifyMsg := new(certificateVerifyMsg)
840 certVerifyMsg.hasSignatureAlgorithm = true
841 certVerifyMsg.signatureAlgorithm = hs.sigAlg
842
843 sigType, sigHash, err := typeAndHashFromSignatureScheme(hs.sigAlg)
844 if err != nil {
845 return c.sendAlert(alertInternalError)
846 }
847
848 signed := signedMessage(serverSignatureContext, hs.transcript)
849 signOpts := crypto.SignerOpts(sigHash)
850 if sigType == signatureRSAPSS {
851 signOpts = &rsa.PSSOptions{SaltLength: rsa.PSSSaltLengthEqualsHash, Hash: sigHash}
852 }
853 sig, err := crypto.SignMessage(hs.cert.PrivateKey.(crypto.Signer), c.config.rand(), signed, signOpts)
854 if err != nil {
855 public := hs.cert.PrivateKey.(crypto.Signer).Public()
856 if rsaKey, ok := public.(*rsa.PublicKey); ok && sigType == signatureRSAPSS &&
857 rsaKey.N.BitLen()/8 < sigHash.Size()*2+2 {
858 c.sendAlert(alertHandshakeFailure)
859 } else {
860 c.sendAlert(alertInternalError)
861 }
862 return errors.New("tls: failed to sign handshake: " + err.Error())
863 }
864 certVerifyMsg.signature = sig
865
866 if _, err := hs.c.writeHandshakeRecord(certVerifyMsg, hs.transcript); err != nil {
867 return err
868 }
869
870 return nil
871 }
872
873 func (hs *serverHandshakeStateTLS13) sendServerFinished() error {
874 c := hs.c
875
876 finished := &finishedMsg{
877 verifyData: hs.suite.finishedHash(c.out.trafficSecret, hs.transcript),
878 }
879
880 if _, err := hs.c.writeHandshakeRecord(finished, hs.transcript); err != nil {
881 return err
882 }
883
884
885
886 hs.masterSecret = hs.handshakeSecret.MasterSecret()
887
888 hs.trafficSecret = hs.masterSecret.ClientApplicationTrafficSecret(hs.transcript)
889 serverSecret := hs.masterSecret.ServerApplicationTrafficSecret(hs.transcript)
890 c.out.setTrafficSecret(hs.suite, QUICEncryptionLevelApplication, serverSecret)
891
892 if c.quic != nil {
893 if c.hand.Len() != 0 {
894
895 c.sendAlert(alertUnexpectedMessage)
896 }
897 c.quicSetWriteSecret(QUICEncryptionLevelApplication, hs.suite.id, serverSecret)
898 }
899
900 err := c.config.writeKeyLog(keyLogLabelClientTraffic, hs.clientHello.random, hs.trafficSecret)
901 if err != nil {
902 c.sendAlert(alertInternalError)
903 return err
904 }
905 err = c.config.writeKeyLog(keyLogLabelServerTraffic, hs.clientHello.random, serverSecret)
906 if err != nil {
907 c.sendAlert(alertInternalError)
908 return err
909 }
910
911 c.ekm = hs.suite.exportKeyingMaterial(hs.masterSecret, hs.transcript)
912
913
914
915
916 if !hs.requestClientCert() {
917 if err := hs.sendSessionTickets(); err != nil {
918 return err
919 }
920 }
921
922 return nil
923 }
924
925 func (hs *serverHandshakeStateTLS13) shouldSendSessionTickets() bool {
926 if hs.c.config.SessionTicketsDisabled {
927 return false
928 }
929
930
931 if hs.c.quic != nil {
932 return false
933 }
934
935
936 return slices.Contains(hs.clientHello.pskModes, pskModeDHE)
937 }
938
939 func (hs *serverHandshakeStateTLS13) sendSessionTickets() error {
940 c := hs.c
941
942 hs.clientFinished = hs.suite.finishedHash(c.in.trafficSecret, hs.transcript)
943 finishedMsg := &finishedMsg{
944 verifyData: hs.clientFinished,
945 }
946 if err := transcriptMsg(finishedMsg, hs.transcript); err != nil {
947 return err
948 }
949
950 c.resumptionSecret = hs.masterSecret.ResumptionMasterSecret(hs.transcript)
951
952 if !hs.shouldSendSessionTickets() {
953 return nil
954 }
955 return c.sendSessionTicket(false, nil)
956 }
957
958 func (c *Conn) sendSessionTicket(earlyData bool, extra [][]byte) error {
959 suite := cipherSuiteTLS13ByID(c.cipherSuite)
960 if suite == nil {
961 return errors.New("tls: internal error: unknown cipher suite")
962 }
963
964
965 psk := tls13.ExpandLabel(suite.hash.New, c.resumptionSecret, "resumption",
966 nil, suite.hash.Size())
967
968 m := new(newSessionTicketMsgTLS13)
969
970 state := c.sessionState()
971 state.secret = psk
972 state.EarlyData = earlyData
973 state.Extra = extra
974 if c.config.WrapSession != nil {
975 var err error
976 m.label, err = c.config.WrapSession(c.connectionStateLocked(), state)
977 if err != nil {
978 return err
979 }
980 } else {
981 stateBytes, err := state.Bytes()
982 if err != nil {
983 c.sendAlert(alertInternalError)
984 return err
985 }
986 m.label, err = c.config.encryptTicket(stateBytes, c.ticketKeys)
987 if err != nil {
988 return err
989 }
990 }
991 m.lifetime = uint32(maxSessionTicketLifetime / time.Second)
992
993
994
995
996 ageAdd := make([]byte, 4)
997 if _, err := c.config.rand().Read(ageAdd); err != nil {
998 return err
999 }
1000 m.ageAdd = byteorder.LEUint32(ageAdd)
1001
1002 if earlyData {
1003
1004 m.maxEarlyData = 0xffffffff
1005 }
1006
1007 if _, err := c.writeHandshakeRecord(m, nil); err != nil {
1008 return err
1009 }
1010
1011 return nil
1012 }
1013
1014 func (hs *serverHandshakeStateTLS13) readClientCertificate() error {
1015 c := hs.c
1016
1017 if !hs.requestClientCert() {
1018
1019
1020 if c.config.VerifyConnection != nil {
1021 if err := c.config.VerifyConnection(c.connectionStateLocked()); err != nil {
1022 c.sendAlert(alertBadCertificate)
1023 return err
1024 }
1025 }
1026 return nil
1027 }
1028
1029
1030
1031
1032 msg, err := c.readHandshake(hs.transcript)
1033 if err != nil {
1034 return err
1035 }
1036
1037 certMsg, ok := msg.(*certificateMsgTLS13)
1038 if !ok {
1039 c.sendAlert(alertUnexpectedMessage)
1040 return unexpectedMessageError(certMsg, msg)
1041 }
1042
1043 if err := c.processCertsFromClient(certMsg.certificate); err != nil {
1044 return err
1045 }
1046
1047 if c.config.VerifyConnection != nil {
1048 if err := c.config.VerifyConnection(c.connectionStateLocked()); err != nil {
1049 c.sendAlert(alertBadCertificate)
1050 return err
1051 }
1052 }
1053
1054 if len(certMsg.certificate.Certificate) != 0 {
1055
1056
1057
1058 msg, err = c.readHandshake(nil)
1059 if err != nil {
1060 return err
1061 }
1062
1063 certVerify, ok := msg.(*certificateVerifyMsg)
1064 if !ok {
1065 c.sendAlert(alertUnexpectedMessage)
1066 return unexpectedMessageError(certVerify, msg)
1067 }
1068
1069
1070
1071
1072 if !isSupportedSignatureAlgorithm(certVerify.signatureAlgorithm, supportedSignatureAlgorithms(c.vers)) ||
1073 !isSupportedSignatureAlgorithm(certVerify.signatureAlgorithm, signatureSchemesForPublicKey(c.vers, c.peerCertificates[0].PublicKey)) {
1074 c.sendAlert(alertIllegalParameter)
1075 return errors.New("tls: client certificate used with invalid signature algorithm")
1076 }
1077 sigType, sigHash, err := typeAndHashFromSignatureScheme(certVerify.signatureAlgorithm)
1078 if err != nil {
1079 return c.sendAlert(alertInternalError)
1080 }
1081 if sigType == signaturePKCS1v15 || sigHash == crypto.SHA1 {
1082 return c.sendAlert(alertInternalError)
1083 }
1084 signed := signedMessage(clientSignatureContext, hs.transcript)
1085 if err := verifyHandshakeSignature(sigType, c.peerCertificates[0].PublicKey,
1086 sigHash, signed, certVerify.signature); err != nil {
1087 c.sendAlert(alertDecryptError)
1088 return errors.New("tls: invalid signature by the client certificate: " + err.Error())
1089 }
1090 c.peerSigAlg = certVerify.signatureAlgorithm
1091
1092 if err := transcriptMsg(certVerify, hs.transcript); err != nil {
1093 return err
1094 }
1095 }
1096
1097
1098
1099 if err := hs.sendSessionTickets(); err != nil {
1100 return err
1101 }
1102
1103 return nil
1104 }
1105
1106 func (hs *serverHandshakeStateTLS13) readClientFinished() error {
1107 c := hs.c
1108
1109
1110 msg, err := c.readHandshake(nil)
1111 if err != nil {
1112 return err
1113 }
1114
1115 finished, ok := msg.(*finishedMsg)
1116 if !ok {
1117 c.sendAlert(alertUnexpectedMessage)
1118 return unexpectedMessageError(finished, msg)
1119 }
1120
1121 if !hmac.Equal(hs.clientFinished, finished.verifyData) {
1122 c.sendAlert(alertDecryptError)
1123 return errors.New("tls: invalid client finished hash")
1124 }
1125
1126 c.in.setTrafficSecret(hs.suite, QUICEncryptionLevelApplication, hs.trafficSecret)
1127
1128 return nil
1129 }
1130
View as plain text